最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React - filter by object property - Stack Overflow

programmeradmin3浏览0评论

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>

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

Share Improve this question edited Apr 25, 2017 at 12:50 KENdi 7,7712 gold badges17 silver badges31 bronze badges asked Apr 25, 2017 at 12:37 Jakub KašparJakub Kašpar 2855 gold badges6 silver badges16 bronze badges 1
  • 1 What is this.state.dataGoal? – dfsq Commented Apr 25, 2017 at 12:40
Add a ment  | 

2 Answers 2

Reset to default 5

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.

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)
发布评论

评论列表(0)

  1. 暂无评论