1

Apologies if my subject line is confusing...simply, what I'm trying to work out is say I have the below arrays:

Array 1

{Hour: "04", Today: 2049},
{Hour: "05", Today: 38},
{Hour: "06", Today: 166}

Array 2

{Hour: "04", Yesterday: 2049},
{Hour: "05", Yesterday: 38},
{Hour: "06", Yesterday: 166}

What would I do to merge these into:

{Hour: "04", Today: 2049, Yesterday: 2049},
{Hour: "05", Today: 38, Yesterday: 38},
{Hour: "06", Today: 166, Yesterday: 166}

I assume I need to reduce it somehow, but I can't quite work it out....

Any help much appreciated...

Lawrence Ferguson
  • 179
  • 2
  • 4
  • 11

1 Answers1

1

You can do it with map and Object.assign()

The map() method will create a new array filled with the results of calling a provided function on every element in the calling array.

The Object.assign() method will copy all enumerable own properties from the source object to a target object and will return the target object.

const arr1 = [{Hour: "04", Today: 2049},
{Hour: "05", Today: 38},
{Hour: "06", Today: 166}];

const arr2 = [{Hour: "04", Yesterday: 2049},
{Hour: "05", Yesterday: 38},
{Hour: "06", Yesterday: 166}];

const arr = arr1.map((el, idx) => Object.assign({}, el, arr2[idx]));

console.log(arr);
Ran Turner
  • 14,906
  • 5
  • 47
  • 53