JavaScript嵌套数组操作:插入对象并按索引拼接商品名与对应数量
你代码的问题出在直接将qty数组和产品名拼接,JS对数组做字符串隐式转换时会把所有元素用逗号拼接,才会出现2,2,2的多余内容。你需要在遍历products时,根据当前遍历的索引取qty数组中对应位置的数值即可。
修正后的完整代码如下:
const data = [ { name: "Order A", orderItems: [ { qty: [2, 2, 2], products: [ { name: "Product A" }, { name: "Product B" }, { name: "Product C" }, ], }, ], }, ]; const dataName = data.map(({ name }) => { return name; }); const product = data.map(({ orderItems }) => { return orderItems.map(({ qty, products }) => { // 新增index参数获取当前产品的遍历下标 return products.map(({ name }, index) => { // 按下标取对应qty值,要去掉"Product "前缀就加.replace('Product ', '') return name.replace('Product ', '') + qty[index]; }); }); }); console.log(`This is ${dataName} with ${product}`);
运行后即可输出A2、B2、C2的预期结果。
内容的提问来源于stack exchange,提问作者Mohammad Khan
相关产品推荐
相关产品推荐

