nun*_*uda 10 javascript arrays object
我有这个对象数组:
var arr = [
{
name: 'John',
contributions: 2
},
{
name: 'Mary',
contributions: 4
},
{
name: 'John',
contributions: 1
},
{
name: 'Mary',
contributions: 1
}
];
Run Code Online (Sandbox Code Playgroud)
...我希望合并重复,但总结他们的贡献.结果如下:
var arr = [
{
name: 'John',
contributions: 3
},
{
name: 'Mary',
contributions: 5
}
];
Run Code Online (Sandbox Code Playgroud)
我怎么能用JavaScript实现这一目标?
Nin*_*olz 11
您可以使用哈希表并生成带有总和的新数组.
var arr = [{ name: 'John', contributions: 2 }, { name: 'Mary', contributions: 4 }, { name: 'John', contributions: 1 }, { name: 'Mary', contributions: 1 }],
result = [];
arr.forEach(function (a) {
if (!this[a.name]) {
this[a.name] = { name: a.name, contributions: 0 };
result.push(this[a.name]);
}
this[a.name].contributions += a.contributions;
}, Object.create(null));
console.log(result);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6821 次 |
| 最近记录: |