如何在对象数组中添加类似键的值

时间:2018-04-12 21:52:52

标签: javascript arrays object keyvaluepair

我有一个对象数组,如下所示:

[
 {1: 22},
 {1: 56},
 {2: 345},
 {3: 23},
 {2: 12}
]

我需要让它看起来像这样:

[{1: 78}, {2: 357}, {3: 23}]

有没有办法让它可以总结所有具有相同键的值?我尝试过为每个循环使用a,但这根本没有帮助。我真的很感激一些帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用reduce来构建新对象。从一个空对象开始,将键设置为原始数组中的值,或者将其添加到现有对象中。然后要获得一个数组,只需将其映射回来。



let arr = [{1: 22},{1: 56},{2: 345},{3: 23},{2: 12}];

let tot = arr.reduce((a,obj) => {
    let [k, v] = Object.entries(obj)[0]
    a[k] = (a[k] || 0) + v
    return a
}, {})

let final = Object.entries(tot).map(([k,v]) => {
    return {[k]:v}
})
console.log(final);




答案 1 :(得分:0)

您可以使用reduce创建总和的对象,然后将该对象转换为对象数组:

function group(arr) {
    var sumObj = arr.reduce(function(acc, obj) {
        var key = Object.keys(obj)[0];                  // get the key of the current object (assuming there is only one)
        if(acc.hasOwnProperty(key)) {                   // if there is an entry of that object in acc
            acc[key] += obj[key];                       // add to it the current object's value
        } else {
            acc[key] = obj[key];                        // otherwise, create a new entry that initially contains the current object's value
        }
        return acc;
    }, {});

    return Object.keys(sumObj).map(function(key) {      // now map each key in sumObj into an individual object and return the resulting objects as an array
        return { [key]: sumObj[key] };
    });
}

示例:



function group(arr) {
    var sumObj = arr.reduce(function(acc, obj) {
        var key = Object.keys(obj)[0];                  // get the key of the current object (assuming there is only one)
        if(acc.hasOwnProperty(key)) {                   // if there is an entry of that object in acc
            acc[key] += obj[key];                       // add to it the current object's value
        } else {
            acc[key] = obj[key];                        // otherwise, create a new entry that initially contains the current object's value
        }
        return acc;
    }, {});

    return Object.keys(sumObj).map(function(key) {      // now map each key in sumObj into an individual object and return the resulting objects as an array
        return { [key]: sumObj[key] };
    });
}

var arr = [ {1: 22}, {1: 56}, {2: 345}, {3: 23}, {2: 12} ];
console.log(group(arr));