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);

How to Check if one array is a subset of another array in Javascript?

I encountered this question in my code today. Although there are a lot of messy ways to do it which it will definitely lead to unmaintainable code, I guess I found the best answer.

Just to remind you, this solution will work if your supported browsers are of ECMA-262 standard. Therefore, for some of you guys out there, this might not work.

The key idea is to use every function in Javascript arrays. According MDN, "Tests whether all elements in the array pass the test implemented by the provided function."

Here is the signature of the method:

array.every(callback[, thisObject])

where callback is a function to test for each element, and thisObject refers to the object that we are testing array against (Remember that in Javascript, arrays are object. Right?)

Here is the snippet:

var arrayOfChildrenNames = ["Amir Rahnama", "Mahshid Rahnama"];
var arrayOfFamilyMemberNames = ["Davood Rahnama", "Maryam Toloo", "Amir Rahnama", "Mahshid Rahnama"];

var isarrayOfNamesSubsetOfFamily = arrayOfChildrenNames.every(function(val) { return arrayOfFamilyMemberNames.indexOf(val) >= 0; }));
console.log(isarrayOfNamesSubsetOfFamily); // true

If you are interested to know more about the function, check out MDN Documentation on Array every method