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

如何点击按钮将customers中itemSold与itemGet的对象合并到products数组

实现点击按钮合并商品数组的方案

首先修正原代码里的两处错误:

  1. 事件绑定里的函数名拼写错误:getProcuts 应该是 getProducts
  2. 事件监听时不能直接调用函数(加括号),要传入函数引用,否则页面加载时就会执行函数,而非点击按钮时触发

接下来是核心的 getProducts 函数实现,我们需要遍历每个客户对象,把他们的 product.itemSold 和 product.itemGet 里的所有商品对象添加到 products 数组中,以下是两种常用实现方式:

方式一:forEach 遍历 + 扩展运算符批量添加

这种方式直观易懂,适合快速理解逻辑:

let customers = [{
    active: true,
    id: 1,
    product: {
      itemSold: [{id:1,name : 'car'}, {id:2,name : 'home'}],
      itemGet: [{id:3,name : 'phone'}, {id:4,name : 'fly'}],
    },
  },
  {
    active: true,
    id: 2,
    product: {
      itemSold: [{id:5,name : 'lamb'}, {id:6,name : 'mouse'}],
      itemGet: [{id:7,name : 'mouse pad'}, {id:8,name : 'tv'}],
    },
  },
];

let clickButton = document.querySelector("#clickButton");
let products = [];

// 修正后的事件绑定
clickButton.addEventListener("click", getProducts);

function getProducts() {
  // 若需每次点击重新生成数组则保留此行,若要累积添加则删除
  products = [];
  
  // 遍历每个客户
  customers.forEach(customer => {
    const { itemSold, itemGet } = customer.product;
    // 用扩展运算符将数组元素逐个添加到products
    products.push(...itemSold, ...itemGet);
  });
  
  // 控制台查看结果
  console.log(products);
}

方式二:flatMap 一次性提取合并

这种方式更简洁,利用数组高阶函数实现:

let customers = [{
    active: true,
    id: 1,
    product: {
      itemSold: [{id:1,name : 'car'}, {id:2,name : 'home'}],
      itemGet: [{id:3,name : 'phone'}, {id:4,name : 'fly'}],
    },
  },
  {
    active: true,
    id: 2,
    product: {
      itemSold: [{id:5,name : 'lamb'}, {id:6,name : 'mouse'}],
      itemGet: [{id:7,name : 'mouse pad'}, {id:8,name : 'tv'}],
    },
  },
];

let clickButton = document.querySelector("#clickButton");
let products = [];

clickButton.addEventListener("click", getProducts);

function getProducts() {
  // flatMap先映射每个客户的商品数组,再扁平化一层得到最终结果
  products = customers.flatMap(customer => [
    ...customer.product.itemSold,
    ...customer.product.itemGet
  ]);
  
  console.log(products);
}

对应的HTML代码保持不变:

<button id="clickButton">Click</button>

补充说明

  • 若需要每次点击按钮都重新生成全新的products数组,保留代码里的products = [];如果希望多次点击不断追加商品,则删除该行。
  • 两种实现方式最终效果完全一致,可根据自己的代码风格选择。

内容的提问来源于stack exchange,提问作者oguzcan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:30:26