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

Node中数组嵌套值的访问与去重,嵌套数据聚合去重求和最简方案

嘿,这个需求其实挺常见的,我给你两种实用的方案——一种用原生ES6/ES7语法(不用额外依赖),另一种用Lodash简化代码,都能高效搞定嵌套数组的去重(按item_code分组)和聚合求和!

先补全你给出的示例数据(方便测试):

const orders = [
  { 
    "orderNumber": "0001", 
    "itemList": [
      { "item_code": "X1000", "qty": 10, "unit_price": 20 }, 
      { "item_code": "X1002", "qty": 10, "unit_price": 20 } 
    ] 
  }, 
  { 
    "orderNumber": "0002", 
    "itemList": [
      { "item_code": "X1000", "qty": 10, "unit_price": 20 }, 
      { "item_code": "X1003", "qty": 5, "unit_price": 15 }
    ]
  }
];
方案一:原生ES6实现(无外部依赖)

用flatMap扁平化嵌套数组,再用reduce分组累加,是最轻量化的方案:

// 第一步:把所有订单的itemList扁平化成一维数组
const allItems = orders.flatMap(order => order.itemList);

// 第二步:按item_code去重并聚合求和
const aggregatedResult = Object.values(allItems.reduce((acc, item) => {
  const key = item.item_code;
  if (!acc[key]) {
    // 首次遇到该商品,初始化条目
    acc[key] = {
      ...item,
      total_amount: item.qty * item.unit_price // 计算初始总金额
    };
  } else {
    // 已有该商品,累加数量和总金额
    acc[key].qty += item.qty;
    acc[key].total_amount += item.qty * item.unit_price;
  }
  return acc;
}, {}));

console.log(aggregatedResult);

输出结果:

[
  { item_code: 'X1000', qty: 20, unit_price: 20, total_amount: 400 },
  { item_code: 'X1002', qty: 10, unit_price: 20, total_amount: 200 },
  { item_code: 'X1003', qty: 5, unit_price: 15, total_amount: 75 }
]
方案二:用Lodash简化代码

如果你项目里已经在用Lodash,用它的链式调用能让代码更简洁直观:

const _ = require('lodash');

const aggregatedResult = _.chain(orders)
  .flatMap('itemList') // 扁平化所有商品项
  .groupBy('item_code') // 按item_code分组
  .mapValues(items => ({
    item_code: items[0].item_code,
    unit_price: items[0].unit_price,
    qty: _.sumBy(items, 'qty'), // 累加数量
    total_amount: _.sumBy(items, i => i.qty * i.unit_price) // 累加总金额
  }))
  .values() // 将分组对象转为数组
  .value();

console.log(aggregatedResult);

这个方案的输出和原生实现完全一致,但代码更紧凑,可读性也不错。

关键思路说明

  • 扁平化数组:不管用原生flatMap还是Lodash的flatMap,都是为了把嵌套在每个订单里的itemList合并成一个一维数组,方便后续处理;
  • 分组去重:用对象(原生方案)或groupBy(Lodash)按item_code作为唯一标识分组,实现去重;
  • 聚合求和:对每个分组内的qty和总金额进行累加,得到最终的聚合结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:16:23