-3

What is the best way to convert:

[2019,2020,2021]

to

{
  0: {year:2019},
  1: {year:2020},
  2: {year:2021}
}
Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

1

Please try this:

a = [2019,2020,2021];
a.reduce((acc, val, idx)=> {acc[idx] = {year: val}; return acc;}, {});
Rinkal Rohara
  • 232
  • 1
  • 7
  • we are creating 1 object out of an array. So we are reducing the array. May would create another array. Though the question does raise the question of whether or not it should be an array instead of an object. – async await Aug 10 '21 at 19:22
0

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);
vanowm
  • 9,466
  • 2
  • 21
  • 37