Friday, November 1, 2013

Merge two object literals into one another in Javascript

I faced this issue a while back that I wanted to achieve something like
var a,b,c;
a = b + c;
for object literals in Javascript. Moreover to that, I wanted to have an option to extend (merge, add or whatever you might want to call it) in a loop, something like the following for the string type:
var result = "",
    j = 0,
    array = ["Amir", "Rahnama"];

    for (; j< array.length;j++) {
       result += array[j] + " ";


console.log(result); //Amir Rahnama
I first tried to write my own code and then suddenly found a better solution: jQuery's extend method. In short, jQuery's extend method extends N objects into a target object:

jQuery.extend( target [, object1 ] [, objectN ] )

The target is an object that will receive the new properties, Object1 is an object containing additional properties to merge in and finally, objectN is the additional objects containing properties to merge in. One way of using the function is like following:
var personObject = {person: {name: "Amir", familyName: "Rahnama"}};
var workObject = { work: {workplace: "Stockholm", companyName: "Gapminder"}};
var personWorkObject = {};
personWorkObject = $.extend(personObject,workObject);
You could also use the method to extend an object recursively, within a loop for example and that is why I highly recommend you to use this method. If you want to extend the objects recursively, make target the return value of the method, like the code below:
personWorkObject = $.extend(personWorkObject, personObject,workObject);

1 comment: