I want to merge two objects and override first object content with second object content.
I tried undescore_.extend()
but the result is not what I want.
var a = {
"firstName": "John",
"lastName": "Doe",
"address": {
"zipCode": "75000",
"city": "Paris"
}
};
var b = {
"firstName": "Peter",
"address": {
"zipCode": "99999"
}
};
merge(a, b); /* fake function */
Expected result :
var a = {
"firstName": "Peter",
"lastName": "Doe",
"address": {
"zipCode": "99999",
"city": "Paris"
}
};
I also tried modules like merge but it did not suit me. How could I do it ?
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments