首页 > 解决方案 > 数组中多个对象的总和值

问题描述

这就是我所拥有的:

const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'},
                {name:'a', amount: 9, test:'FAIL'}, 
                {name:'b', amount: 15, serviceId: '23b', test:'SUCCESS'}]

 

(请注意,有些对象没有“serviceId”)

我想得到:

 [{name:'a', amount: 19, test:'FAIL'},
  {name:'b', amount: 15, test:'SUCCESS'}]

我已经搜索过,并尝试过这样的事情:(参考:https ://stackoverflow.com/a/50338360/13840216 )

const result = Object.values(arrayA.reduce((r, o) => (r[o.name]
  ? (r[o.name].amount += o.amount)
  : (r[o.name] = {...o}), r), {}));

但仍然不确定如何分配test字段。

任何帮助,将不胜感激!

标签: javascripttypescriptreduce

解决方案


如有必要,您需要检查test并更新该值。

const
    array = [{ name: 'a', amount: 10, serviceId: '23a', test: 'SUCCESS' }, { name: 'a', amount: 9, test: 'FAIL' }, { name: 'b', amount: 15, serviceId: '23b', test: 'SUCCESS' }],
    result = Object.values(array.reduce((r, { name, amount, test }) => {
        if (!r[name]) r[name] = { name, amount: 0, test };
        r[name].amount += amount;
        if (test === 'FAIL') r[name].test = 'FAIL';
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读