-2

I have 2 two level JavaScript structures, which I need to merge. What would be the easiest way?

var object1={
  "section1": {
    "prop1": 0,
    "prop2": 0
  },
  "section2": {
    "something": 0,
    "other": 0
  }
}

var object2={
  "section1": {
    "prop1": 1
  }
}

object2 contains changes made in the UI by user and I need to get the merged object, showing all the data, with only those properties present in object2 overwritten by object2's values.

Kokesh
  • 3,165
  • 7
  • 29
  • 46
  • So result for section1 should be only `"prop1": 0` without `prop2`? – Nenad Vracar Aug 18 '16 at 11:28
  • @NenadVracar Object1 is full configuration, which is loaded from the device. Object2 contains only changes made by the user, not yet saved into the device (need them to be merged into 1st object, so I can send the original config, with newly changed options included, to the device). I've updated the source - object2.section1.prop1 has now value 1, which I would like to merge into object1. – Kokesh Aug 18 '16 at 11:51
  • So result for section1 is prop1 and prop2 with prop1 updated from object2 – Nenad Vracar Aug 18 '16 at 11:52
  • 1
    Possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – trincot Aug 18 '16 at 12:04

2 Answers2

1

You can do this with Object.keys() and reduce() and update each object if key is found i object2 with Object.assign().

var object1={
  "section1": {
    "prop1": 0,
    "prop2": 0
  },
  "section2": {
    "something": 0,
    "other": 0
  }
}

var object2={
  "section1": {
    "prop1": 5
  }
}

var result = Object.keys(object1).reduce(function(r, k) {
  if(object2[k]) {
    r[k] = Object.assign({}, object1[k], object2[k]);
  } else {
    r[k] = object1[k];
  }
  return r;
}, {});

console.log(result);
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

var mergedObj = Object.assign({}, object1, object2) if I understood your question correctly.

flott
  • 231
  • 1
  • 11