Let's say in my component I set the state like so:
this.setState({
test: "value",
othertest: "value"
});
If, elsewhere in my code, I have an array containing the keys for these values, ie- keys = ["test", "othertest"]
how can I loop through this array to find the value of the corresponding state value?
The state and props in React are always in an object format. This means that the value could be accessed from the state and props via key-value pair. To access the normal state object, you can use the key name from the object.
Step 1: Create a react application by typing the following command in the terminal. Step 2: Now, go to the project folder i.e project_name by running the following command. Example: Let us create an input field that takes the state name as input and state value as another input.
State is an object, so you can access any value by:
this.state[key]
Use any loop map, forEach
etc to iterate the array
and access the value by this.state[key]
, like this:
a.forEach(el => console.log(this.state[el]))
Check this snippet:
let state = {a: 1, b: 2};
let arr = ['a', 'b'];
let values = arr.map(el => state[el])
console.log(values);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With