Reputation: 47
I'm trying to loop through 2 of the key value pairs in my state. They both have very similar names the only difference between them is that one ends in Day and the other ends in Night. Here is a simplified example of my project right now. My objective is for the log to come out with the results shown below:
state = {
energyType: "Electricity",
meterRate: "oneRate",
firstEnergyAmountDay: 1,
firstEnergyAmountNight: 2,
}
let days
if (this.state.energyType === "Electricity" && this.state.meterRate === "twoRate") {
days = ["Day", "Night"]
} else {
days = ["Day"]
}
days.map(day => {
console.log(this.state.firstEnergyAmount + day);
})
Right now my log just returns:
undefinedDay
undefinedNight
And I want the log to give me:
1
2
Upvotes: 1
Views: 30
Reputation: 84912
To do a computed property of an object, you need to use square brackets and a string
console.log(this.state["firstEnergyAmount" + day])
So that will concatenate strings together to produce either "firstEnergyAmountDay"
or "firstEnergyAmountNight"
, and then the square brackets will look up the property with that key.
Upvotes: 1