假设我有一个包含这样对象的数组
array = [
{id:2,cnt:2},{id:3,cnt:3},{id:4,cnt:2},
{id:1,cnt:6},{id:2,cnt:7},{id:5,cnt:4},
{id:2,cnt:4},{id:3,cnt:2},{id:4,cnt:2},
{id:3,cnt:2},{id:4,cnt:3},{id:5,cnt:2}
];
我需要用对象创建另一个数组,我需要用 id
添加 cnt
值。
输出应该是这样的。
output = [
{id:1,cnt:6},{id:2,cnt:13},{id:3,cnt:7},{id:4,cnt:7},{id:5,cnt:6}
];
到目前为止我尝试过的是
var general = [];
angular.forEach(array, function(value){
angular.forEach(value, function(val,key){
angular.forEach(general, function(val1,key1){
if(val1.id === val.id){
val1.cnt +=val.cnt
//@TOD0 how to add value of count and put it on general
}else{
//@TODO
general.push(val);
}
});
});
});
console.log(general);
我无法实现我的输出。我已将我感到困惑的地方标记为 TODO。有人能帮我吗?提前致谢。
最佳答案
Array.reduce
可以帮到您很多 - 您基本上是创建一个新数组,然后迭代当前数组并检查新数组以查看当前项是否存在。如果是,则添加 cnt
- 否则添加整个项目:
var mashed = arr.reduce(function(m, cur, idx) {
var found = false;
for (var i =0; i < m.length; i++) {
if (m[i].id == cur.id) {
m[i].cnt += cur.cnt;
found = true;
}
}
if (!found) {
m.push(cur)
}
return m;
}, [])
fiddle 演示:https://jsfiddle.net/1ffqv9g0/
关于javascript - 检查一个键值是否已经存在于angularjs中的多维数组对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41023206/