Wednesday, May 18, 2011

javascript merge two arrays/objects

I just want to simulate PHP's array_merge function in javascript.

So how to merge two normal arrays in javascript? The answer is Array.concat method. Check this code:
var o1 = [1, 2], o2 = ['a','b'];
//we will have an array [1,2,'a','b']
console.log(o1.concat(o2));

How about objects? Javascript object is actually the concept of associative array in PHP:
var o1 = {category:'living', name:'unknown'};
var o2 = {name:'henry', gender:'m'}

Well, we have to copy each property of the objects into a new object. So, finally, the general function to merge two arrays/objects in javascript:

var mergeObjects = function(objOne, objTwo) {
        if (objOne instanceof Array) {
            return objOne.concat(objTwo);
        }
        var merge = {};
        var property;
        for (property in objOne) {
            merge[property] = objOne[property];
        }
        for (property in objTwo) {
            merge[property] = objTwo[property];
        }
        return merge;
}

That is it. It is easy to be modified to be more generic and robust.

No comments: