Aggregate/concatenate JavaScript objects in an array based on 2 keys?

时间:2017-03-02 23:32:41

标签: javascript arrays concatenation

I have this array input:

[
{
    a:1
    b:1
    c: 100
},
{
    a:1
    b:1 
    : 150
},
{
    a:1
    b:2
    c: 100
},
{
    a:2
    b:1
    c:13
}
]

And I want a array result like this:

[
{
    a:1
    b:1
    c: 250  
},

{
    a:1
    b:2
    c: 100
},
{
    a:2
    b:1
    c:13
}
]

My idea is to combine two objects by adding them together if and only if at least TWO specific keys are the exact same. I know there's code on this site to do Javascript to combine multiple objects based on one key being the exact same, but it won't work for this purpose. How would I do it?

1 个答案:

答案 0 :(得分:0)

You can create one object to store key-value pairs of specific properties that you want to group objects by, and then use reduce() to return object as result.

var data = [{"a":1,"b":1,"c":100},{"a":1,"b":1,"c":150},{"a":1,"b":2,"c":100},{"a":2,"b":1,"c":13}]

var hash = {}
var result = data.reduce(function(r, e) {
  var key = 'a'+e.a+'|b'+e.b;
  if(!hash[key]) hash[key] = e, r.push(hash[key])
  else hash[key].c += e.c
  return r
}, [])

console.log(JSON.stringify(result, 0, 4))