3

I have two objects and I want to merge them, but it should not replace the object.

var x = {'one':1, 'two': {'b': 2, 'c': 3}}
var y = {'two': {'b': 4}}

When I merge them The out put should be :

{'one':1, 'two': {'b': 4, 'c': 3}}
George
  • 6,630
  • 2
  • 29
  • 36
KRUSHANU MOHAPATRA
  • 552
  • 1
  • 6
  • 18
  • [There are no such things as JSON objects](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) those are just plain JS Objects. – George Jul 28 '17 at 07:58

1 Answers1

3

You can use recursive approach for updating nested object.

var x = {
  'one': 1,
  'two': {
    'b': 2,
    'c': 3
  }
}
var y = {
  'two': {
    'b': 4
  }
}


function merge(a, b) {
// create new object and copy the properties of first one
  var res = Object.assign({}, a);
  //iterate over the keys of second object
  Object.keys(b).forEach(function(e) {
    // check key is present in first object
    // check type of both value is object(not array) and then
    // recursively call the function
    if (e in res && typeof res[e] == 'object' && typeof res[e] == 'object' && !(Array.isArray(res[e]) || Array.isArray(b[e]))) {
   // recursively call the function and update the value 
   // with the returned ne object
   res[e] = merge(res[e], b[e]);
    } else {
      // otherwise define the preperty directly
      res[e] = b[e];
    }
  });
  return res;
}

var res = merge(x, y);

console.log(res);

UPDATE : If you want to merge the array then you need to do something like this.

var x = {
  'one': 1,
  'two': {
    'b': [22, 23],
    'c': 3
  }
}
var y = {
  'two': {
    'b': [24]
  }
}


function merge(a, b) {
  var res = Object.assign({}, a);
  Object.keys(b).forEach(function(e) {
    if (e in res && typeof res[e] == 'object' && typeof res[e] == 'object' && !(Array.isArray(res[e]) || Array.isArray(b[e]))) {
      res[e] = merge(res[e], b[e]);
      // in case both values are array 
    } else if (Array.isArray(res[e]) && Array.isArray(b[e])) {
      // push the values in second object
      [].push.apply(res[e], b[e]);
      // or use 
      // res[e] = res[e].concat(b[e]);
    } else {
      res[e] = b[e];
    }
  });
  return res;
}

var res = merge(x, y);

console.log(res);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188