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
keys() to filter an Object. After you've generated the keys, you may use filter() to loop over the existing values and return just those that meet the specified criteria. Finally, you can use reduce() to collect the filtered keys and their values into a new object, for instance.
To find an object in an array in React: Call the find() method on the array, passing it a function. The function should return an equality check on the relevant property. The find() method returns the first value in the array that satisfies the condition.
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With