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

JavaScript多维数组合并:汇总paid字段并整合用户信息

合并JavaScript数组:相同产品条目汇总paid并整合用户信息

需求说明

合并数据库返回的JavaScript数组,将相同产品的条目合并:

  • 汇总paid字段的数值
  • 单个username字段整合为usernames数组;若仅单条产品记录,保留原username字段格式

输入示例

const array = [
  {
    name: 'Iphone',
    date: '01.01.2024',
    img: 'img/iphone.png',
    cost: 2500,
    paid: 500,
    username:"Joe",
  },
  {
    name: 'Samsung',
    date: '01.01.2024',
    img: 'img/samsung.png',
    cost: 2000,
    paid: 200,
    username:"Adam",
  },
  {
    name: 'Samsung',
    date: '01.01.2024',
    img: 'img/samsung.png',
    cost: 2000,
    paid: 100,
    username:"Alvin",
  }
];

期望输出

const array = [
  {
    name: 'Iphone',
    date: '01.01.2024',
    img: 'img/iphone.png',
    cost: 2500,
    paid: 500,
    username:"Joe",
  },
  {
    name: 'Samsung',
    date: '01.01.2024',
    img: 'img/samsung.png',
    cost: 2000,
    paid: 300,
    usernames:[
      {username : "Adam"},
      {username : "Alvin"}
    ]
  }
];

解决方案代码

const array = [
  { name: 'Iphone', date: '01.01.2024', img: 'img/iphone.png', cost: 2500, paid: 500, username:"Joe" },
  { name: 'Samsung', date: '01.01.2024', img: 'img/samsung.png', cost: 2000, paid: 200, username:"Adam" },
  { name: 'Samsung', date: '01.01.2024', img: 'img/samsung.png', cost: 2000, paid: 100, username:"Alvin" }
];

// 执行合并逻辑
const mergedArray = Object.values(array.reduce((acc, item) => {
  const key = item.name;
  if (!acc[key]) {
    // 初始化新的产品条目
    acc[key] = { ...item };
    delete acc[key].username;
    acc[key].usernames = [{ username: item.username }];
  } else {
    // 累加paid数值
    acc[key].paid += item.paid;
    // 添加新用户到数组
    acc[key].usernames.push({ username: item.username });
  }
  return acc;
}, {})).map(product => {
  // 单用户条目格式转换
  if (product.usernames.length === 1) {
    const { usernames, ...rest } = product;
    return { ...rest, username: usernames[0].username };
  }
  return product;
});

console.log(mergedArray);

代码说明

  1. 分组与累加:通过reduce()按产品name分组,首次创建条目时初始化usernames数组,后续条目直接累加paid并追加用户信息;
  2. 格式统一:最后用map()处理单用户场景,将usernames数组转换回单个username字段,匹配示例输出格式;
  3. 字段保留:除username/usernames外,其他产品字段(如date、img、cost)均完整保留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:23:18