合并深层对象并覆盖

时间:2016-01-20 19:45:38

标签: javascript node.js

我想合并两个对象,并用第二个对象内容覆盖第一个对象内容。

我尝试了不受欢迎的 _.extend(),但结果并不是我想要的。

e.g

对象:
var a = {
    "firstName": "John",
    "lastName": "Doe",
    "address": {
        "zipCode": "75000",
        "city": "Paris"
    }
};

var b = {
    "firstName": "Peter",
    "address": {
        "zipCode": "99999"
    }
};

merge(a, b); /* fake function */
预期结果:
var a = {
    "firstName": "Peter",
    "lastName": "Doe",
    "address": {
        "zipCode": "99999",
        "city": "Paris"
    }
};

我也试过像merge这样的模块,但它不适合我。 我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

Try following

Object.deepExtend = function(destination, source) {
  for (var property in source) {
     if (typeof source[property] === "object" &&
       source[property] !== null ) {
       destination[property] = destination[property] || {};
       arguments.callee(destination[property], source[property]);
     } else {
       destination[property] = source[property];
     }
  }
};


var a = {
    "firstName": "John",
    "lastName": "Doe",
    "address": {
        "zipCode": "75000",
        "city": "Paris"
    }
};

var b = {
    "firstName": "Peter",
    "address": {
        "zipCode": "99999"
    }
};

Object.deepExtend(a,b);

console.dir(a);