Reputation: 645
How can I merge these two objects in javascript?
h1 = {12: [{actor: 'wayne'}, {actor: 'bill'}], 13: [{actor: 'james'}]}
h2 = {13: [{actor: 'mark'}]}
to get:
result = {12: [{actor: 'wayne'}, {actor: 'bill'}], 13: [{actor: 'james'}, {actor: 'mark'}]}
Basically I want to concat the arrays, based on the keys of the objects.
Upvotes: 2
Views: 2405
Reputation: 382112
You could do that :
for (var k in h2) {
h1[k]=(h1[k]||[]).concat(h2[k]);
}
The resulting object would be h1.
Demonstration (open the console)
If you want to left h1 unchanged, do this :
h3 = {};
for (var k in h1) h3[k]=h1[k].slice();
for (var k in h2) h3[k]=(h3[k]||[]).concat(h2[k]);
Upvotes: 6