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()
})
}
CodePudding user response:
[...Array(number).keys()].map(i => ({ value: i 1, label: (i 1).toString() }))
CodePudding user response:
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)