Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - filter by object property

I am trying to filter object by property but I can't make it work.

Data in the object are structured like so:

enter image description here

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

like image 209
Jakub Kašpar Avatar asked Apr 25 '17 12:04

Jakub Kašpar


People also ask

How do you use object filters?

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.

How get values from array of objects in React?

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.

How do you filter an array of objects?

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.


1 Answers

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.

like image 103
dfsq Avatar answered Sep 29 '22 03:09

dfsq