React - filter by object property

拟墨画扇 提交于 2019-12-22 06:49:40

问题


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


回答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)



回答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.



来源:https://stackoverflow.com/questions/43610859/react-filter-by-object-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!