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()
    })
}
2

2 Answers 2

2
[...Array(number).keys()].map(i => ({ value: i + 1, label: (i + 1).toString() }))
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.