Snailer
Snailer

Reputation: 3839

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 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?

Upvotes: 13

Views: 32499

Answers (2)

James Kraus
James Kraus

Reputation: 3478

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

Upvotes: 2

Mayank Shukla
Mayank Shukla

Reputation: 104369

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

Upvotes: 21

Related Questions