React - filter by object property
Solution 1
Object.keys
returns the keys
of that object, meaning that it returns an array of strings with every key in that object.
obj = { 'a': 1, 'b': 2 };
Object.keys(obj); // ['a', 'b']
So to access the value of that property you have to access it using that key, in your case it would be something like this:
filter(key => this.state.dataGoal[key].main == true)
Solution 2
Assuming that this.state.dataGoal
is the object from posted goals array, then your filter is wrong. Should be:
{Object.keys(this.state.dataGoal)
.filter(key => this.state.dataGoal[key].main === true)
.map((key, index) => {
return <div key={key}>
<h1>{this.state.dataGoal[key].name}</h1>
<p>{this.state.dataGoal[key].main}</p>
</div>
})}
Note, that now it's .filter(key => this.state.dataGoal[key].main === true)
because key is the string, something like Khasdfasdfasdfasdfads
and you want to access goal
object by this key in order to check its main
property.
Jakub Kašpar
Updated on April 26, 2020Comments
-
Jakub Kašpar about 4 years
I am trying to filter object by property but I can't make it work.
Data in the object are structured like so:
I am fetching data by the UID and then mapping all the items from that object but I can't make the filter work.
Render method looks like so:
render() { return( <div> {Object.keys(this.state.dataGoal) .filter(key => key.main == true) .map( (key, index) => { return <div key={key}> <h1>{this.state.dataGoal[key].name}</h1> <p>{this.state.dataGoal[key].main}</p> </div> })} </div>
Any ideas what I am doing wrong?
Thanks for any help, Jakub