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);
      

Run code


+4


source


Thanks to the array access syntax, you can access an object's property (like state) using a variable:

let state = {a: 1, b: 2}
let myKey = 'a';

console.log(state[myKey]) // 1
      

Run code




So, to get all values ​​for an array of keys, map your array of keys and get the state value for each key.

let values = keys.map(key => this.state[key])

+1


source







All Articles