Combining JavaScript objects in an array with same key value

后端 未结 4 863
太阳男子
太阳男子 2020-12-19 18:21

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,          


        
4条回答
  •  庸人自扰
    2020-12-19 19:08

    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});
    });
    

提交回复
热议问题