【问题标题】:How to add values of similar keys in an array of object如何在对象数组中添加相似键的值
【发布时间】:2018-04-13 06:21:34
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • myarray['1'][] = 'stuff';

标签: javascript arrays object keyvaluepair


【解决方案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);

【讨论】:

  • 这对我有用!太感谢了!我试图使用 Object.keys 而不是 Object.entries 并且对如何在对象是数字时引用对象的键感到困惑。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2019-02-17
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 2019-03-14
    相关资源
    最近更新 更多