NodeJS中如何获取未知键的嵌套键值对的键与值?
解决方案
获取所有商家ID与对应数据
如果你需要处理merchants对象中所有的键值对,可以用*Object.entries()*方法,它会直接返回键和值组成的二维数组:
const merchants = req.body.merchants; // 遍历所有商家条目 for (const [merchantId, dataList] of Object.entries(merchants)) { console.log('商家ID:', merchantId); // 输出 6RDH804A896K1 console.log('对应数据:', dataList); // 输出对应的数组 }
仅获取单个商家(已知只有一个键时)
如果确定merchants里只有一个商家条目,可以用*Object.keys()*取第一个键:
const merchants = req.body.merchants; const merchantId = Object.keys(merchants)[0]; const merchantData = merchants[merchantId]; console.log(merchantId, merchantData);
TypeScript 类型修正
你之前的类型定义写法错误,正确的索引签名应该这样写,用来描述“键是字符串、值是指定结构数组”的对象:
// 先定义单个数据项的类型 interface MerchantItem { objectId: string; type: string; ts: number; } // 定义merchants的类型:字符串键对应MerchantItem数组 type MerchantsObj = { [key: string]: MerchantItem[]; }; // 类型断言或直接定义 const merchants: MerchantsObj = req.body.merchants;
这样后续操作时TypeScript就能正确推导类型,避免报错。
内容的提问来源于stack exchange,提问作者coder123
相关产品推荐
相关产品推荐

