0

I am trying to create an array (todos) with the same objects in the state of my React Component. The object is supposed to consist of an active:false, value and its index.

I tried this:

this.state = {
      todos:Array(15).fill({active:false},{idx:???})
}

What do I write as the index?

2 Answers 2

1

You can skip .fill by spreading Array(15) into an array and then you can just .map. But why are you making an empty array first if you already have values that you want to populate?

[...Array(15)].map((_, idx) => {
  return {active: false, idx}
})
Sign up to request clarification or add additional context in comments.

2 Comments

oh, i have exactly 15 todos and only need to update their status. So I thought I'm creating them in the constructor and then just update their status based on their index. Is that correct ?
Made a syntax mistake. Above works. As long as your implementation works, then by all means use it.
1

You can write an index in array as idx to the object:

Array(15).fill({ active: false }).map((i, k) => ({ ...i, ...{ idx: k }}));

But you need to use map to iterate throw array one more time and create a new array with indexes.

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.