-3

I have an array 1:

['a', 'b', 'c']

And array 2:

[{ a: 1, b: 2, c: 3, d: 5 }]

How to combine 2 arrays as below:

[{a: 1, b: 2: c: 3}]

The result only includes the items in first array. I want an optimal solution.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Alber Z
  • 27
  • 5
  • Please share what have you tried so far? – Karan Jul 23 '20 at 10:42
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Jul 23 '20 at 10:42
  • Thanks! I will learn from experience for next time – Alber Z Jul 23 '20 at 11:00

1 Answers1

0

A solution using reduce

a1 = ['a', 'b', 'c', 'e'];
a2 = [{ a: 1, b: 2, c: 4, d: 5 }];

a = a1.reduce((a,key) => [... a, {[key]: a2[0][key]}], []);


console.log(a);

In case a key from the first array is missing in the second array, its value will be set as undefined.

user2314737
  • 27,088
  • 20
  • 102
  • 114