If state is something do .filter & .map otherwise only .map

I am even not sure if it's possible to do it this way but I'll try to explain what I want to accomplish.

Im trying to filter & map an array where labels.attributes.label === this.state.currentLabel

And Im getting it to work. But If this.state.currentLabel === 'All' I only want to do .map and not make .filter

Is there any conditional logic I can implement to get this to work?

Here is how the code looks now:

{podcasts.filter((labels) => labels.attributes.label === this.state.currentLabel)
  .map((pod) => {
    const podId = pod.id.attributes['im:id']
    const podName = pod['im:name'].label

    return <PodcastItem key={podId} id={podId} name={podName} />
})}

And sorry if I am bad at explaining.. Im fairly new to coding. So just make comment if I can describe it better.

3 answers

  • answered 2018-10-11 19:35 ashish singh

    instead of chaining like

    let ans = data.filter(..)
               .map(..)
    

    you can do

    let filtered = data; 
    
    if( /* your state condition */) {
      filtered = data.filter(...)
    }
    
    let ans = filtered.map(...)
    

  • answered 2018-10-11 19:35 Ted

    You can inline it like so:

     {podcasts
        .filter(
          labels =>
            this.state.currentLabel === 'All'
              ? labels
              : labels.attributes.label === this.state.currentLabel,
        )
        .map(pod => {
          const podId = pod.id.attributes['im:id'];
          const podName = pod['im:name'].label;
    
          return <PodcastItem key={podId} id={podId} name={podName} />;
        });
     }
    

  • answered 2018-10-11 19:37 cars10m

    Simply add another condition to your filter function (with ||) and you are done:

    {podcasts.filter((labels) => this.state.currentLabel ===labels.attributes.label || this.state.currentLabel==='All')
      .map((pod) => {
        const podId = pod.id.attributes['im:id']
        const podName = pod['im:name'].label
    
        return <PodcastItem key={podId} id={podId} name={podName} />
    })}