Search code examples
javascriptjsonnode.jsextend

JSON extend without overwriting attributes with same name


I need to extend my JSON data. Now I have two objects:

const obj1 = {
   "data": [
      {
         "fruit num": 1,
         "kind": "sweet"
      },
      {
         "fruit num": 2,
         "kind": "sour"
      }
   ]
}

const obj2 = {
   "data": [
      {
         "fruit num": 3,
         "kind": "bitter"
      },
      {
         "fruit num": 4,
         "kind": "bitter"
      }
   ]
}

What I need to do is to make an obj3 file which would look like this:

const obj3 = {
   "data": [
      {
         "fruit num": 1,
         "kind": "sweet"
      },
      {
         "fruit num": 2,
         "kind": "sour"
      },
      {
         "fruit num": 3,
         "kind": "bitter"
      },
      {
         "fruit num": 4,
         "kind": "bitter"
      }
   ]
}

When I try to use obj3 = obj1.concat(obj2) - it says there is no such function.

When I try to use obj3 = Object.assign(obj1, obj2) - it overwrites the JSON file and then there are only 2 fruits left.

When I try to use obj3.data = Object.assign(obj1.data, obj2.data) - it does not change anything.

And yes, the {data:[]} is a must here.

How can I extend the JSON object without overwriting it?

P.S. I am using Node 8 here.


Solution

  • You need to explicitly combine the data arrays to do that:

    const obj3 = { data: [...obj1.data, ...obj2.data] };
    

    If there are other properties in the two objects that you also want to combine into obj3, then you can Object.assign and pass a third object made up of the combined data:

    const obj3 = Object.assign({}, obj1, obj2, { data: [...obj1.data, ...obj2.data] });
    

    Or, more concisely, with object spread:

    const obj3 = {
      ...obj1,
      ...obj2,
      data: [...obj1.data, ...obj2.data]
    };