-1

how can I merge two objects of objects into one object?

Example

let obj1 = {monkey:{size: 120, color: "black"}, cat: {size: 30, color: "gray"}}

let obj2 = {monkey:{country: "africa", test: "test"}, cat: {country: "all", testCat: "testCat"}}

Output should be :

{monkey:{size: 120, color: "black", country: "africa", test: "test"}, cat: {size: 30, color: "gray", country: "all", testCat: "testCat"}}

I dont know how many animals are there.

something like this

let merged = {...obj1, ...obj2}
otto
  • 1,815
  • 7
  • 37
  • 63
  • How about you provide an example of the output, should there be repetition or not ? – Rainbow Jun 02 '18 at 23:46
  • i have edited... – otto Jun 02 '18 at 23:54
  • You are basically looking for https://www.npmjs.com/package/json-merge that would look on an additional "dimension". Check how that package does it and adapt it to suit your needs. – Ravenous Jun 03 '18 at 00:04

1 Answers1

0

We need to know how many Object we have to merge so i grouped them in an array.

this solution may look bad but it works :)

let obj1 = {
  monkey: {
    size: 120,
    color: "black"
  },
  cat: {
    size: 30,
    color: "gray"
  }
};

let obj2 = {
  monkey: {
    country: "africa",
    test: "test"
  },
  cat: {
    country: "all",
    testCat: "testCat"
  }
};

let objects = [obj1, obj2];
let output = {};



objects.map(function(obj) {
  var keys = Object.keys(obj);
  keys.map(function(key) {
    if (!output[key])
      output[key] = obj[key];
    else {
      var keyss = Object.keys(obj[key]);
      keyss.map(function(item) {
        output[key][item] = obj[key][item];
      });
    }
  });
});



console.log(output);

Optimized using the arrow function.

objects.map(obj =>Object.keys(obj).map(key => output[key] ?  Object.keys(obj[key]).map( item =>output[key][item] = obj[key][item] ) : output[key] = obj[key] ));
Rainbow
  • 6,772
  • 3
  • 11
  • 28