6

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.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Armand
  • 23,463
  • 20
  • 90
  • 119
  • If a property contains another object or an array, do you want a new copy or a reference to that property in the new object? – jfriend00 Jun 22 '12 at 16:36
  • What question is this a duplicate of? – Armand Jun 22 '12 at 16:38
  • var a = {a:1, c:4}; var b = {b:2, f:9, d:4}; var c = combine(a, b); function combine(array1, array2) { for (key in array2) { array1[key] = array2[key]; } return array1 } – Tarun Jun 22 '12 at 16:42
  • 1
    @Alison: Look at the top of your question: http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically – Felix Kling Jun 22 '12 at 16:44

1 Answers1

4

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...

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758