Merge objects in JavaScript -
this question has answer here:
- how deep merge instead of shallow merge? 16 answers
i have 2 objects , want merge them, should not replace object.
var x = {'one':1, 'two': {'b': 2, 'c': 3}} var y = {'two': {'b': 4}}
when merge them out put should :
{'one':1, 'two': {'b': 4, 'c': 3}}
you can use recursive approach updating nested object.
var x = { 'one': 1, 'two': { 'b': 2, 'c': 3 } } var y = { 'two': { 'b': 4 } } function merge(a, b) { // create new object , copy properties of first 1 var res = object.assign({}, a); //iterate on keys of second object object.keys(b).foreach(function(e) { // check key present in first object // check type of both value object(not array) , // recursively call function if (e in res && typeof res[e] == 'object' && typeof res[e] == 'object' && !(array.isarray(res[e]) || array.isarray(b[e]))) { // recursively call function , update value // returned ne object res[e] = merge(res[e], b[e]); } else { // otherwise define preperty directly res[e] = b[e]; } }); return res; } var res = merge(x, y); console.log(res);
update : if want merge array need 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 array } else if (array.isarray(res[e]) && array.isarray(b[e])) { // push 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);
Comments
Post a Comment