gpt4 book ai didi

javascript - 如何对数组中的对象进行分组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:30:19 24 4
gpt4 key购买 nike

我有一个对象数组,我想根据两个键对它的对象进行分组

var arr = [ 
{"name": "apple", "id": "apple_0","c":'20'},
{"name": "dog", "id": "dog_1","c":'10'},
{"name": "apple", "id": "apple_0","c":'30'},
{"name": "dog", "id": "dog_1","c":'10'},
];

我期待的结果是

var final = [ 
{"name": "apple", "id": "apple_0","c":'50'},
{"name": "dog", "id": "dog_1","c":'20'}
];

场景是这样的 - 我想根据 nameid 对对象进行分组。如果在最终数组中找到 nameid,则对其 c 求和。

我试过这个:

var final = [];
for(var i = 0; i<arr.length; i++){
var obj = {};
obj = arr[i];
for(var j = 0; j<final.length; j++){
if((obj[name] !== final[j].name) && (obj[id] !== final[j].id)){
final.push(obj)
}else{
//addition of key `c` in existing object in `final` array
}
}
}

但内部 for 循环不起作用,并且由于连续循环执行而挂起我的系统。

请让我知道如何修复它或任何其他逻辑以获得最终结果。

最佳答案

这是一个使用哈希表#reduce() 函数的解决方案 - 请参见下面的演示:

var arr = [{"name": "apple", "id": "apple_0","c":'20'},{"name": "dog",   "id": "dog_1","c":'10'}, {"name": "apple", "id": "apple_0","c":'30'},{"name": "dog",   "id": "dog_1","c":'10'}];

var result = arr.reduce(function(hash){
return function(p,c){
if(hash[c.id])
hash[c.id].c = +hash[c.id].c + +c.c
else {
hash[c.id] = hash[c.id] || c;
p.push(hash[c.id]);
}
return p;
}
}(Object.create(null)), []);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

关于javascript - 如何对数组中的对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45749289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com