2

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.

1
  • I'm afraid you'll have to do the dirty work yourself. Not even jQuery.extend anticipates this use-case. Maybe Underscore will. Commented Jan 4, 2013 at 17:36

1 Answer 1

6

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]); 
Sign up to request clarification or add additional context in comments.

7 Comments

I would think concat needed shimming but no... :-)
Shim = compatibility layer. Very popular means of adding ES5 support (read: lots of functionality) to ES3 browsers (read: IE8)
@JanDvorak OK. Got It. But concat is one of those very old standard functions. I guess we don't have much in mind because it's rarely useful.
In the second version, you could also sacrifice a small amount of performance(?) for symmetry and write the first loop as for (var k in h1) h3[k]=(h3[k]||[]).concat(h1[k]);
I don't really remember what is "very old standard" and what is "shiny new that should have been very old standard" when it comes to cross-browser javascript.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.