How do you combine two objects in javascript?

Possible duplicate:
How can I combine the properties of two JavaScript objects dynamically?

If I have two Javascript objects that I use as a list of key-value pairs:

var a = {a:1};
var b = {b:2};

What is the most efficient way to combine them into a third object that contains the properties of both?

var c = {a:1, b:2};

I do not mind if one or both of aand were changed in the process b.

+5
source share
1 answer

You can do it simply:

   var c = {};
   for (var key in a) {
      c[key] = a[key];
   }
   for (var key in b) {
      c[key] = b[key];
   }

If you want to do deep merging (if you don't want to copy functions and prototypes), you can use this:

  function goclone(source) {
        if (Object.prototype.toString.call(source)==='[object Array]') {
            var clone = [];
            for (var i=0; i<source.length; i++) {
                if (source[i]) clone[i] = goclone(source[i]);
            }
            return clone;
        } else if (typeof(source)=="object") {
            var clone = {};
            for (var prop in source) {
                if (source[prop]) {
                    var firstChar = prop.charAt(0);
                    clone[prop] = goclone(source[prop]);
                }
            }
            return clone;
        } else {
            return source;
        }
    }


   var c = {};
   for (var key in a) {
      c[key] = goclone(a[key]);
   }
   for (var key in b) {
      c[key] = goclone(b[key]);
   }

But honestly, I have never seen use for deep merging in javascript ...

+5

All Articles