Convert Array to Object with key name

158 Views Asked by At

What is the best way to convert:

[2019,2020,2021]

to

{
  0: {year:2019},
  1: {year:2020},
  2: {year:2021}
}
2

There are 2 best solutions below

1
Rinkal Rohara On

Please try this:

a = [2019,2020,2021];
a.reduce((acc, val, idx)=> {acc[idx] = {year: val}; return acc;}, {});
0
vanowm On

Combination of Object.assign() and array.map() comes to mind:

const array = [2019,2020,2021];

const object = Object.assign({}, array.map(a => ({year: a})));
console.log("object:", object);


const object2 = {}
array.forEach((a, i) => object2[i] = {year: a});
console.log("object2:", object2);