Get state value using dynamic key in react
Let's say in my component I set the state like this:
this.setState({
test: "value",
othertest: "value"
});
If elsewhere in my code I have an array containing the keys for these values, i.e. keys = ["test", "othertest"]
, how can I go through this array to find the value of the corresponding state value?
+3
source to share
2 answers
State is an object , so you can access any value with:
this.state[key]
Use any loop map, forEach
, etc., to iterate array
and access the value this.state[key]
, for example:
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);
+4
source to share