How do you combine two objects in Javascript?

10,032

You can do simply this :

   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 a deep merging (assuming you don't want to copy the 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 frankly I never saw the use for a deep merging in javascript...

Share:
10,032
Armand
Author by

Armand

Updated on June 27, 2022

Comments

  • Armand
    Armand almost 2 years

    Possible Duplicate:
    How can I merge properties of two JavaScript objects dynamically?

    If I have two Javascript objects which I am using 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 which contains the properties of both?

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

    I don't mind if either or both of a and b are modified in the process.