0

is there a shorthand approach to creating an array of objects of length X in js other than using a for loop? This is to use for react select npm package

end result

const options = [
  { value: 1, label: "1" },
  { value: 2, label: "2" },
  { value: 3, label: "3" },
];

for loop approach

let options = []
for (let i = 1; i <= 10; i++) { // assume arbitrary length 10
    options.push({
        value: i,
        label: i.toString()
    })
}
user3226932
  • 2,042
  • 6
  • 39
  • 76

2 Answers2

2
[...Array(number).keys()].map(i => ({ value: i + 1, label: (i + 1).toString() }))
Konrad
  • 21,590
  • 4
  • 28
  • 64
1

You can use Array.from() with a mapping function to creat your objects:

const res = Array.from({length: 10}, (_, i) => ({value: i+1, label: (i+1).toString()}))

This creates the array and fills it with the appropriate objects in the one iteration (rather than performing multiple iterations)

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64