【问题标题】:How to merge duplicates in an array of objects and sum a specific property? [duplicate]如何合并对象数组中的重复项并对特定属性求和? [复制]
【发布时间】:2016-11-12 16:23:11
【问题描述】:

我有这个对象数组:

var arr = [
    {
        name: 'John',
        contributions: 2
    },
    {
        name: 'Mary',
        contributions: 4
    },
    {
        name: 'John',
        contributions: 1
    },
    {
        name: 'Mary',
        contributions: 1
    }
];

...我想合并重复项但总结他们的贡献。结果将如下所示:

var arr = [
    {
        name: 'John',
        contributions: 3
    },
    {
        name: 'Mary',
        contributions: 5
    }
];

我如何使用 JavaScript 实现这一点?

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

您也可以使用 linq.js 提供的 linq 框架来完成此操作

这是我使用 linq.js 的代码,几乎看起来像 sql 语句。

var arr = [
    {
        name: 'John',
        contributions: 2
    },
    {
        name: 'Mary',
        contributions: 4
    },
    {
        name: 'John',
        contributions: 1
    },
    {
        name: 'Mary',
        contributions: 1
    }
];


var aggregatedObject = Enumerable.From(arr)
        .GroupBy("$.name", null,
                 function (key, g) {
                     return {
                       name: key,
                       contributions: g.Sum("$.contributions")
                     }
        })
        .ToArray();

console.log(aggregatedObject);
<script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>

【讨论】:

    【解决方案2】:

    您可以使用哈希表并根据需要生成一个包含总和的新数组。

    var arr = [{ name: 'John', contributions: 2 }, { name: 'Mary', contributions: 4 }, { name: 'John', contributions: 1 }, { name: 'Mary', contributions: 1 }],
        result = [];
    
    arr.forEach(function (a) {
        if (!this[a.name]) {
            this[a.name] = { name: a.name, contributions: 0 };
            result.push(this[a.name]);
        }
        this[a.name].contributions += a.contributions;
    }, Object.create(null));
    
    console.log(result);

    【讨论】:

    • 你可以使用全新的 ES6 Map 对象:var result = new Map(); arr.forEach((element) => { if (result.get(element.name)) result.set(element.name, result.get(element.name) + element.contributions); else result.set(element.name, element.contributions); }); console.log(result);
    • @mplungjan 我喜欢你的方法
    • @mplungjan 成功了,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多