Reputation:
I got a problem with loop and states. How to display states info in loop if I want to union part of state name and number?
In JS file I have constructor:
constructor(props) {
super(props);
this.state = {
fruit_1: 'apple',
fruit_2: 'orange',
fruit_3: 'bannana',
fruit_4: 'apple',
}
}
And loop:
for (var i = 1; i < 5; i++) {
console.log(this.state.fruit_i);
{/* Here is a problem. Calls undefined, but if I write this.state.fruit_1 -> displays correctly. */}
{/* How to union counter with this state name? */}
}
Upvotes: 1
Views: 38
Reputation: 1826
Loop on the state directly:
var state = {
fruit_1: 'apple',
fruit_2: 'orange',
fruit_3: 'bannana',
fruit_4: 'apple',
};
for (var key in state) {
console.log(state[key]);
}
Upvotes: 0
Reputation: 59491
Try the code below. It builds the string you need:
constructor(props) {
super(props);
this.state = {
fruit_1: 'apple',
fruit_2: 'orange',
fruit_3: 'bannana',
fruit_4: 'apple',
}
}
for (var i = 1; i < 5; i++) {
console.log(this.state["fruit_" + i]);
}
state = {
fruit_1: 'apple',
fruit_2: 'orange',
fruit_3: 'bannana',
fruit_4: 'apple',
}
for (var i = 1; i < 5; i++) {
console.log(this.state["fruit_" + i]);
}
Though I would suggest using an array to store the fruits, if possible. Like this:
constructor(props) {
super(props);
this.state = {
fruits: ["apple", "orange", "banana", "apple"]
}
}
for (var i = 1; i < 5; i++) {
console.log(this.state.fruits[i]);
}
Upvotes: 0
Reputation: 62536
You will need to build the name of the index.
Here is one example:
state = {
fruit_1: 'apple',
fruit_2: 'orange',
fruit_3: 'bannana',
fruit_4: 'apple',
}
for (var i = 1; i < 5; i++) {
console.log(state[`fruit_${i}`]);
}
In your code you would use:
console.log(this.state[`fruit_${i}`]);
Upvotes: 1