Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
136 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...