Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge objects in JavaScript [duplicate]

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}}
like image 963
KRUSHANU MOHAPATRA Avatar asked Jan 01 '26 02:01

KRUSHANU MOHAPATRA


1 Answers

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);
like image 144
Pranav C Balan Avatar answered Jan 03 '26 15:01

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!