我希望合并两个对象,并用第二个对象内容覆盖第一个对象内容。
我试过undescore_.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"
}
};我也尝试过像合并这样的模块,但它不适合我。我怎么能做到呢?
发布于 2016-01-20 19:57:34
试着跟随
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);
https://stackoverflow.com/questions/34909125
复制相似问题