我想为以下 java 脚本关联数组添加验证。
这是我的数组结构
array = [
{ id: 1, remaining_amount: 30, total: 20 },
{ id: 1, remaining_amount: 30, total: 20 },
{ id: 2, remaining_amount: 50, total: 40 }
]
从上面的数组中,对于id 1,剩余数量为30,但总数量为40
所以我想添加验证,如果总金额大于特定 id 的剩余金额,那么它会显示消息。
有什么想法吗?
最佳答案
您可以使用reduce
和filter
使用reduce
来汇总总数。并使用 filter
获取所有那些 total
大于 remaining_amount
var array = [{ id: 1, remaining_amount: 30, total: 20 },{ id: 1, remaining_amount: 30, total: 20 },{ id: 2, remaining_amount: 50, total: 40 }];
var result = Object.values(array.reduce((c, v) => {
c[v.id] = c[v.id] || {id: v.id,remaining_amount: v.remaining_amount,total: 0};
c[v.id].total += v.total;
return c;
}, {})).filter(o => o.remaining_amount < o.total);
console.log(result);
关于javascript - 如何为javascript关联数组添加验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49624204/