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?
答案 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))