Merge objects using $.extend() in jQuery

Have you ever come across a requirement in which you need merge many objects in one object? Okay let me clarify question in simpler words. Assume you have two objects as given below. object1 is defined as below,


var object1 = {
 red: 0,
 blue: { lightblue: 24, darkblue: 12 },
 black: 17
 };

And another object is object2.


var object2 = {
 white: 200,
 blue: {lightblue:40}
 };

Let us say you have to merge object2 in object1. Here merge means merging properties of object2 in object1. You can do this in jQuery using extend() function.


$.extend(object1, object2);
 console.log(object1);

 

Let us say you have to merge object2 in object1. Here merge means merging properties of object2 in object1. You can do this in jQuery using extend() function.

Now if you go ahead and view console you see following output. As you can see value for blue property in object1 has been changed with the value of object2’s blue property.

image

This is the way $.bind() merge two objects in jQuery. There could be another scenario in which you want to merge objects recursively. Recursively means property value which is unique in target object will persist. For recursive binding you need to set first parameter as True.

 $.extend(true,object1, object2);
 console.log(object1);

In output you can see that now blue property of object1 has darkblue and lightblue both. Value of darkblue has been modified with object2 property value.

image

You can merge more than two objects as below and always remember that $.bind returns target object as output,


var object1 = {
 red: 0,
 blue: { lightblue: 24, darkblue: 12 },
 black: 17
 };
 var object2 = {
 white: 200,
 blue: { lightblue: 40 }
 };

 
 var object3 =
 {
 yellow: 234
 };
 var targetresult = $.extend({}, object1, object2, object3);
 console.log(targetresult);

 

In this way you can merge objects in JavaScript using jQuery $.bind() function. I hope you find this post useful. Thanks for reading.

About these ads

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