You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 00:39:03