Skip to content
Advertisement

How do I merge two Javascript Objects into one?

I Have two Array of Objects :

salesLabelData

JavaScript

salesAPIData :

JavaScript

]

I need to merge these, to eventually get this array (Basically the Datasets have to be merged into one) :

Expected Result –

JavaScript

I have tried the following and other various permutations/combinations, checked out many answers on this site but none worked:

JavaScript

I am missing something, not sure what and hence am not able to get the desired result, Any Help is sincerely appreciated.

Advertisement

Answer

You’ll need to have a kind of deep merge. It seems that we can assume that:

  • the data types of data that occurs in the same place in both data structures, are guaranteed to be the same;
  • the arrays that occur in the same place in both data structures, are guaranteed to have the same size;
  • the primitive values that occur in the same place in both data structures (strings, numbers, …) are guaranteed to be the same.

It’s too bad that you want to merge properties that have different names (dataSets, datasets), so some code is needed to deal with that. But it would be better to correct this at the source.

Here is some suggested code:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement