1

I am new to the react native, How to Merge two java script object array. Using object.assign() , it works but it will overwrite the same field.

Array1 = {
  '2018-12-15': { marked:true, dotColor:'red' },
  '2018-12-16': { marked:true, dotColor:'red' },
  '2018-12-17': { marked:true, dotColor:'red' },
}

Array2 = {
  '2018-12-15': { marked:true, dotColor:'green' },
  '2018-12-26': { marked:true, dotColor:'green' },
  '2018-12-27': { marked:true, dotColor:'green' },
}

Output should be:

Result = {
  '2018-12-15': { marked:true, dotColor:'red' },
  '2018-12-16': { marked:true, dotColor:'red' },
  '2018-12-17': { marked:true, dotColor:'red' },
  '2018-12-15': { marked:true, dotColor:'green' },
  '2018-12-26': { marked:true, dotColor:'green' },
  '2018-12-27': { marked:true, dotColor:'green' },
 }
Robbie Milejczak
  • 5,664
  • 3
  • 32
  • 65
Binisha
  • 167
  • 1
  • 1
  • 8
  • Hey it seems like maybe you tagged this as `react-native` on accident. This problem would get better assistance tagged as `javascript` – Robbie Milejczak Dec 28 '18 at 15:18

1 Answers1

0

What you're trying to do is not possible because an object cannot have a duplicate property. Think about it, if your object has two properties called 2018-12-15:

const result = {
  '2018-12-15': value,
  '2018-12-15': value2,
}

how could you access them both? result['2018-12-15'] now has a totally ambiguous value and it's for that reason that javascript objects cannot have duplicate keys.

If you want to merge the objects you could do something simple like this:

const result = { ...Array2, ...Array1 }

Which outputs:

{
  '2018-12-15'. : { marked:true,dotColor:'red' },
  '2018-12-16'. : { marked:true,dotColor:'red' },
  '2018-12-17'. : { marked:true,dotColor:'red' },
  '2018-12-26'. : { marked:true,dotColor:'green' },
  '2018-12-27'. : { Bmarked:true,dotColor:'green' },
}

This is called object spreading, basically I "unpackaged" the two initial objects and wrapped them in brackets to create one new object. The final properties are determined based on which object is placed last, so

const result = { ...Array1, ...Array2 }

will output:

{
  '2018-12-15': {marked: true, dotColor: "green"},
  '2018-12-16': {marked: true, dotColor: "red"},
  '2018-12-17': {marked: true, dotColor: "red"},
  '2018-12-26': {marked: true, dotColor: "green"},
  '2018-12-27': {marked: true, dotColor: "green"}
}

If you want even greater control of how objects are merged you can use the built in reduce method

Robbie Milejczak
  • 5,664
  • 3
  • 32
  • 65