对象数组(JavaScript)合并并添加具有相同键

时间:2015-09-18 18:33:56

标签: javascript arrays object dictionary merge

我有一组像这样的对象:

array = [{item_name: "necklace", quantity: "2"},
         {item_name: "necklace", quantity: "4"},
         {item_name: "bracelet", quantity: "5"}];

我想在数组中合并这些对象,最终得到一个如下所示的数组:

array = [{item_name: "necklace", quantity: "6"},
         {item_name: "bracelet", quantity: "5"}];

我不确定如何开始解决这个问题。我尝试过concat和merge但是这些覆盖了值。我需要映射吗?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

您只需循环遍历数组并将值推送到新数组中,首先检查item_name是否已存在。

检查对象是否已在新数组中的更简单方法是创建一个item_name对象及其在新数组中的位置。否则,每次检查时都需要循环遍历新数组。

试试这个:

function merge_data(array){
    var new_array = [],
        item_map = {};

    // Loop over the array
    array.forEach(function(v){
        var item = v.item_name;

        // The object is not already in the new array
        if(item_map[item] === undefined){
            // Push the object and save its index
            item_map[item] = new_array.length;
            // WARNING: This pushes a *reference* to `v` into the new array
            // which means when I update `new_array[pos]`, it'll also update
            // this object in the *original* array
            //new_array.push(v);

            new_array.push({
                item_name: item,
                quantity: v.quantity
            });
        }
        // The object is already in the new array
        else{
            // Get its index and update the quantity
            var pos = item_map[item],
                // quantity is a string, we need to make it into an int
                quantity = parseInt(new_array[pos].quantity, 10);

            new_array[pos].quantity = quantity + parseInt(v.quantity, 10);
        }
    });

    return new_array;
}

// Now `array` will have the merged data
array = merge_data(array);
console.log(array);