我有两个对象数组,例如:
var A = [{title:"name1",count:5},{title:"name2",count:1},{title:"name3",count:3}];
和:
var B = [{title:"name2",count:7},{title:"name3",count:2},{title:"name4",count:3},{title:"name5",count:8}];
我需要将这两个数组合并到一个数组中,并在“title”属性相同时对返回数组中的“count”值求和: 最后的答案必须是:
[{title:"name1",count:5},{title:"name2",count:8},{title:"name3",count:5},{title:"name4",count:3},{title:"name5",count:8}]
我该怎么做???
最佳答案
您可以使用Array#forEach和 Array#some取得成果
var M = A.concat(B)
var C = [];
M.forEach(function(a) {
var index;
if (C.some(function(c, i) { index = i; return a.title == c.title; })) {
C[index].count += a.count;
} else {
C.push(a);
}
});
console.log(C); // as you expect
关于javascript - 使用 JavaScript 自定义比较函数合并两个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35783595/