在js中聚合数组内的对象

我有一个如下所示的数组:


 {"sku": 123, "val": 10},

 {"sku": 124, "val":12},

 {"sku": 123, "val": 20}


]

javascript 中是否有一种快速方法可以对val具有相同 sku 属性的对象求和,因此结果将是:


 {"sku": 123, "val": 30},

 {"sku": 124, "val":12}

]


HUX布斯
浏览 155回答 4
4回答

慕桂英546537

您可以使用javascript的reduce函数const array = [  { "sku": 123, "val": 10 }, { "sku": 124, "val": 12 }, { "sku": 123, "val": 20 }];const result = [];array.reduce((res, value) => {  if (!res[value.sku]) {    res[value.sku] = { "sku": value.sku, "val": 0 };    result.push(res[value.sku])  }  res[value.sku].val += value.val;  return res;}, {});console.log(result)

慕工程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; }

慕神8447489

跟踪对象中的总和:const arr = [     {"sku": 123, "val": 10},    {"sku": 124, "val":12},    {"sku": 123, "val": 20}];const sums = {};for (const {sku, val} of arr) {    if (!(sku in sums)) {        sums[sku] = 0;    }    sums[sku] += val;}const result = Object.entries(sums).map(([k, v]) => ({sku: k, val: v}));console.log(result);

桃花长相依

用于forEach构建一个带有键sku和值进行聚合的对象。从上面的对象中获取。Object.valuesconst group = (arr) => {  const res = {};  arr.forEach(({sku, val}) => {    res[sku] ? (res[sku].val += val) : res[sku] = { sku, val };  });  return Object.values(res);};const arr = [  { sku: 123, val: 10 },  { sku: 124, val: 12 },  { sku: 123, val: 20 },];console.log(group(arr));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript