Skip to content Skip to sidebar Skip to footer

Get State Value By A Dynamic Key In React

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 t

Solution 1:

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

Solution 2:

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

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

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

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

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


Post a Comment for "Get State Value By A Dynamic Key In React"