How do you combine two objects in Javascript?

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.


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

链接地址: http://www.djcxy.com/p/27330.html

上一篇: 将节点JS中的一个json对象更新为另一个json对象

下一篇: 你如何在Javascript中结合两个对象?