合并具有相同键值的JavaScript对象并对其进行计数

时间:2017-02-07 14:41:23

标签: javascript arrays

我正在尝试将具有相同键值的对象合并为一个并计算它们。它甚至可能吗?

    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,
}]
}

4 个答案:

答案 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;
}, [])

小提琴:https://jsfiddle.net/6wqw79pn/

答案 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];
  }
}

工作示例:https://jsfiddle.net/mspinks/5kowbq4j/3/

答案 2 :(得分:0)

基本上,您可以使用值为id的哈希表作为键和计数。

&#13;
&#13;
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;
&#13;
&#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)