Search code examples
javascriptjavascript-objects

Merging two objects while keeping matching keys


I'm trying to merge two javascript objets which, both have same similear key, but diffrent values. I want them to keep the diffrent keys and but place themn together in the matching parent object.

For example:

const obj1 = {
   "title" : {
     "en-US" : "Some title"
   },
   "text": {
     "en-US": "Some text"
   }
 }
 const obj2 = {
   "title" : {
     "de-DE" : "Some diffrent title"
   },
   "text": {
     "de-DE": "Some diffrent text"
   }
 }

Desired Result:

{
    "title" : {
      "en-US" : "Some title",
      "de-DE" : "Some diffrent title"
    },
    "text": {
      "en-US": "Some text"
      "de-DE": "Some diffrent text"
    }
  }

What I tried:

Object.assign and the ES6 variant gave me this:

const mergedObj = {...obj1, ...obj2}

console.log(mergedObj);

    {
        "title" : {
          "de-DE" : "Some diffrent title"
        },
        "text": {
          "de-DE": "Some diffrent text"
        }
      }

Solution

  • You can get the keys of one of your objects, and map that to a new object, which merges the values for that key from both objects into one. You can then using Object.assign() to merge your array of mapped objects into a single resulting object like so:

    const obj1 = { "title" : { "en-US" : "Some title" }, "text": { "en-US": "Some text" } } 
    const obj2 = { "title" : { "de-DE" : "Some diffrent title" }, "text": { "de-DE": "Some diffrent text" } }
    
    const merge_objs = (o1, o2) =>
      Object.assign({}, ...Object.keys(o1).map(k => ({[k]: {...o1[k], ...o2[k]}})));
     
    console.log(merge_objs(obj1, obj2));