根据数组中的 ID 汇总记录并合并
Summing Records and Consolidating Based on IDs in Array
我有一个包含对象的记录数组,每个对象都有一个 id
和一个 amount
。现在,在这个数组中,一些元素具有相同的 id。我需要做的是遍历这个数组,首先,对具有相同 id 的记录的值求和,然后 return 只是一个记录 - 所以我最终得到一个数组只有唯一的 ID——每个 ID 还包含一个 amount
属性.
换句话说,我要取这个数组:
const records = [
{id: 1, amount: 10},
{id: 1, amount: 20},
{id: 2, amount: 10},
{id: 3, amount: 10},
{id: 3, amount: -10}
];
... 并生成此数组:
const transformedRecords = [
{id: 1, amount: 30},
{id: 2, amount: 10},
{id: 3, amount: 0}
];
我考虑过为此使用 for-of
循环,但这可能会非常冗长,而且我猜想有更简洁的方法来完成此操作 - 也许使用 reduce()
?什么是解决这个问题的优雅方法,最好使用 es6+ 语法?
您可以使用 reduce()
创建对象,然后在其条目上使用 map()
创建对象数组
const records = [
{id: 1, amount: 10},
{id: 1, amount: 20},
{id: 2, amount: 10},
{id: 3, amount: 10},
{id: 3, amount: -10}
];
const res = Object.entries(records.reduce((ac, a) => {
ac[a.id] = (a[a.id] || 0) + a.amount;
return ac
}, {})).map(([id, amount]) => ({id, amount: amount < 0 ? 0 : amount}))
console.log(res)
使用Array.reduce
,对于每次迭代,检查accumulator
中是否有当前id
的对象,如果有,添加amounts
,如果不是,则将当前对象推送到 accumulator
:
const records = [
{id: 1, amount: 10},
{id: 1, amount: 20},
{id: 2, amount: 10},
{id: 3, amount: 10},
{id: 3, amount: -10},
{id: 4, amount: -10},
{id: 4, amount: -10}
];
const result = records.reduce((acc, curr) => {
const ndx = acc.findIndex(e => e.id === curr.id);
if(ndx > -1) {
acc[ndx].amount += curr.amount
}
else{
acc.push(curr)
}
return acc;
}, [])
console.log(result)
我有一个包含对象的记录数组,每个对象都有一个 id
和一个 amount
。现在,在这个数组中,一些元素具有相同的 id。我需要做的是遍历这个数组,首先,对具有相同 id 的记录的值求和,然后 return 只是一个记录 - 所以我最终得到一个数组只有唯一的 ID——每个 ID 还包含一个 amount
属性.
换句话说,我要取这个数组:
const records = [
{id: 1, amount: 10},
{id: 1, amount: 20},
{id: 2, amount: 10},
{id: 3, amount: 10},
{id: 3, amount: -10}
];
... 并生成此数组:
const transformedRecords = [
{id: 1, amount: 30},
{id: 2, amount: 10},
{id: 3, amount: 0}
];
我考虑过为此使用 for-of
循环,但这可能会非常冗长,而且我猜想有更简洁的方法来完成此操作 - 也许使用 reduce()
?什么是解决这个问题的优雅方法,最好使用 es6+ 语法?
您可以使用 reduce()
创建对象,然后在其条目上使用 map()
创建对象数组
const records = [
{id: 1, amount: 10},
{id: 1, amount: 20},
{id: 2, amount: 10},
{id: 3, amount: 10},
{id: 3, amount: -10}
];
const res = Object.entries(records.reduce((ac, a) => {
ac[a.id] = (a[a.id] || 0) + a.amount;
return ac
}, {})).map(([id, amount]) => ({id, amount: amount < 0 ? 0 : amount}))
console.log(res)
使用Array.reduce
,对于每次迭代,检查accumulator
中是否有当前id
的对象,如果有,添加amounts
,如果不是,则将当前对象推送到 accumulator
:
const records = [
{id: 1, amount: 10},
{id: 1, amount: 20},
{id: 2, amount: 10},
{id: 3, amount: 10},
{id: 3, amount: -10},
{id: 4, amount: -10},
{id: 4, amount: -10}
];
const result = records.reduce((acc, curr) => {
const ndx = acc.findIndex(e => e.id === curr.id);
if(ndx > -1) {
acc[ndx].amount += curr.amount
}
else{
acc.push(curr)
}
return acc;
}, [])
console.log(result)