Jonas Alvarson
Jonas Alvarson

Reputation: 471

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.

Upvotes: 0

Views: 38

Answers (3)

Carsten Massmann
Carsten Massmann

Reputation: 28196

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} />
})}

Upvotes: 1

Ted
Ted

Reputation: 14927

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} />;
    });
 }

Upvotes: 1

ashish singh
ashish singh

Reputation: 6904

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(...)

Upvotes: 2

Related Questions