慕工程0101907
您应该按 SKU 对条目进行分组,然后将条目映射到 SKU 和减少的值(总和)。const data = [ { "sku": 123, "val": 10 }, { "sku": 124, "val": 12 }, { "sku": 123, "val": 20 }];const groupBy = (arr, key) => arr.reduce((acc, entry) => ({ ...acc, [entry[key]]: [ ...(acc[entry[key]] || []), entry ]}), {}); const sum = Object.entries(groupBy(data, 'sku')) .map(([key, values]) => ({ 'sku': key, 'val': values.reduce((acc, { val }) => acc + val, 0) }))console.log(sum);.as-console-wrapper { top: 0; max-height: 100% !important; }这是一个更加动态的版本,允许使用具有各种聚合技术的多个减速器。const groupBy = (arr, key) => arr.reduce((acc, entry) => ({ ...acc, [entry[key]]: [ ...(acc[entry[key]] || []), entry ]}), {}); const aggregate = (arr, key, reducers) => Object.entries(groupBy(arr, key)) .map(([k1, values]) => Object.entries(reducers) .reduce((obj, [k2, { fn, initial }]) => ({ ...obj, [k2]: values.reduce((acc, item, index, all) => fn(acc, item[k2], index, all), initial || 0) }), { [key]: k1 }))const data = [ { "sku": 123, "val": 10, "val2": 2 }, { "sku": 124, "val": 12, "val2": 5 }, { "sku": 123, "val": 20, "val2": 8 }];const aggregated = aggregate(data, 'sku', { 'val' : { fn: (acc, val) => acc + val, initial: 0 }, 'val2' : { fn: (acc, val) => acc * val, initial: 1 }});console.log(aggregated);.as-console-wrapper { top: 0; max-height: 100% !important; }