合并深层对象并覆盖

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

我试着不_.extend()但结果不是我想要的。

例如

对象:

 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" } }; 

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

尝试以下

 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);