Javascript : jQuery : How to merge two json obects or Hashes in JS?

Suppose,

hashOne = {
  first_elm: 'I am first',
  second_elm: 'I am sec'
};
hashTwo = {
  third_elm: 'I am third',
  fourth_elm: 'I am fourth'
};

we cannot simply append the second to the first like

var newHash = hashOne + hashTwo
>> "[object Object][object Object]"

However, jQuery has a helper method to merge two hashes..

Example:

newHash = $.extend({}, hashOne, hashTwo);
>> Object {first_elm: "I am first", second_elm: "I am sec", third_elm: "I am third", fourth_elm: "I am fourth"}

 

If you do as following

newHash = $.extend(hashOne, hashTwo);

you will have the `hashOne` modified

> hashOne
> Object {first_elm: "I am first", second_elm: "I am sec", third_elm: "I am third", fourth_elm: "I am fourth"}

One thought on “Javascript : jQuery : How to merge two json obects or Hashes in JS?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s