Merge deep objects and override

auk

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.

e.g

Objects :
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 ?

Nikhil Aggarwal

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.

edited at
0

Comments

0 comments
Login to comment

Related