在相同键值的数组结合JavaScript对象 [英] Combining JavaScript objects in an array with same key value

查看:100
本文介绍了在相同键值的数组结合JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图与对象相同的id值数组里面结合起来。我有数组是这样的:

I have been trying to combine objects inside an array with same id-value. The array that I have is like this:

[
{"id" : "abcd","val1" : 1,"val2": 1, "val3" : 0},
{"id" : "abcd","val1" : 1,"val2": 1, "val3" : 1},
{"id" : "efgh","val1" : 0,"val2": 0, "val3" : 1}
]

我一直试图找到一种方法来组合这些,这样的结果会是这样:

I have been trying to find a way to combine these so that the result would be like this:

[
{"id" : "abcd","val1" : 2,"val2": 2, "val3" : 1},
{"id" : "efgh","val1" : 0,"val2": 0, "val3" : 1}
]

是否有某种方式与 underscore.js

推荐答案

这应该以下划线的功能方法做到这一点:

This should do it with underscore's functional approach:

_.map(_.groupBy(arr, "id"), function(vals, id) {
    return _.reduce(vals, function(m, o) {
        for (var p in o)
            if (p != "id")
                m[p] = (m[p]||0)+o[p];
        return m;
    }, {id: id});
});

这篇关于在相同键值的数组结合JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆