javascript - 数组中多个对象的总和值
问题描述
这就是我所拥有的:
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'}]
- 我想对
amount
按名称分组的字段求和。 - 'test' 字段应该是
FAIL
是否有任何具有该值的对象FAIL
(按名称分组) - 我不关心它的价值,
serviceId
也不想将它包含在新对象中。
我已经搜索过,并尝试过这样的事情:(参考: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
字段。
任何帮助,将不胜感激!
解决方案
如有必要,您需要检查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; }
推荐阅读
- angular - 在Angular中将UTC时间戳转换为PST
- java - DiffUtil 未调用 onBindView 或刷新 ViewHolder
- python - 为什么使用 Librosa 时我的内存会增长?
- jquery - rails 6 / webpacker tooltip and popover event listeners TypeError: $(...).tooltip is not a function
- javascript - 开发人员工具的网络选项卡中不存在内容安全策略
- sql - 子查询返回超过 1 个值。当子查询遵循 SQL Server 过程时,这是不允许的
- python - 如何使用investpy获取实时股市数据?
- python - a / b,但如果 b == 0 则返回 0
- javascript - Javascript - 查找重复项,合并并推送新数组以及唯一项
- reactjs - 使用扩展运算符组合多个数组在 React JS 中获取数据