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

How to add values of similar keys in an array of object

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

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

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

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

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

您可以使用 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);

您可以使用 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));