我正在尝试将具有相同键值的对象合并为一个并计算它们。它甚至可能吗?
var array = {
"items": [{
"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 10,
"id": "111",
"name": "BlackCat",
}, {
"value": 15,
"id": "777",
"name": "WhiteCat",
}]
}
期望的输出:
var finalArray = {
"items": [{
"value": 10,
"id": "111",
"name": "BlackCat",
"count": 2,
}, {
"value": 15,
"id": "777",
"name": "WhiteCat",
"count": 1,
}]
}
答案 0 :(得分:4)
您可以在reduce
阵列上使用items
:
var combinedItems = array.items.reduce(function(arr, item) {
var found = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i].id === item.id) {
found = true;
arr[i].count++;
}
}
if (!found) {
item.count = 1;
arr.push(item);
}
return arr;
}, [])
答案 1 :(得分:0)
您可以使用for
循环:
var finalArray = [];
for (var i in array.items) {
var item = array.items[i];
var existingItem = finalArray.find(function(element){
return (element.id == item.id);
});
if (!existingItem) {
existingItem = {};
finalArray.push(existingItem);
} else {
if (!existingItem.count)
existingItem.count = 2;
else
existingItem.count++;
}
for (var j in item) {
existingItem[j] = item[j];
}
}
答案 2 :(得分:0)
基本上,您可以使用值为id
的哈希表作为键和计数。
var object = { items: [{ value: 10, id: "111", name: "BlackCat", }, { value: 10, id: "111", name: "BlackCat", }, { value: 15, id: "777", name: "WhiteCat", }] },
result = object.items.reduce(function (hash) {
return function (r, o) {
if (!hash[o.id]) {
hash[o.id] = { value: o.value, id: o.id, name: o.name, count: 0 };
r.push(hash[o.id]);
}
hash[o.id].count++;
return r;
};
}(Object.create(null)), []);
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 3 :(得分:0)
Underscore js将能够轻松解决您的问题
var groups = _.groupBy(array.items, function(item){
return item.value + '#' + item.id + '#' + item.name;
});
var data = {'items' : []};
_.each(groups,function(group){
data.items.push({
'value' : group[0].value,
'id' : group[0].id,
'name' : group[0].name,
'count' : group.length
})
})
console.log(data)