0xburned
0xburned

Reputation: 2655

Returning a new set of array using map method

How do I return a new set of array using map based on 2 conditions:

This is my original response looks like

enter image description here

React function which maps the response

_getList(memberships) {
    const items = memberships.map((membership) => {
        return (
            <RadioButton
                value={membership.forum.slug}
                label={membership.forum.title} />
        );
    });

    return(
        <RadioButtonGroup>
            {items}
        </RadioButtonGroup>
    );
}

In my render function I am checking if the length is not 0

const renderedList = this._getList(UserStore.getState().memberships.length !== 0);

How should I add another check that the new array returned should only contains the data with role === moderator

Upvotes: 0

Views: 71

Answers (2)

Mark
Mark

Reputation: 6081

Using filter

_getList(memberships) {
    const items = (memberships.filter(membership => membership.role === 'moderator') || []).map((membership) => {
        return (
            <RadioButton
                value={membership.forum.slug}
                label={membership.forum.title} />
        );
    });

    if(items.length === 0) return null;

    return(
        <RadioButtonGroup>
            {items}
        </RadioButtonGroup>
    );
}

then you could do this:

const renderedList = this._getList(UserStore.getState().memberships);

if(renderedList) {
    this.renderSomething();
} else {
    this.renderSomethingElse();
}

Upvotes: 1

Emil Oberg
Emil Oberg

Reputation: 4046

You want to take a look at the .filter method of the Array API.

const items = memberships
    .filter(item => item.role === 'moderator')
    .map((membership) => {
        return (
            <RadioButton
                value={membership.forum.slug}
                label={membership.forum.title} />
        );
    })

.filter will iterate through all member of the array and return a new array with all elements that pass the test implemented by the provided function. If the memberships array is empty, it'll simple return an empty array.

This assumes that the memberships property always is an array. Either an array with values in it, or an empty array ([]). If the memberships property can be missing, you still need to add a check such as your renderedList one.

Upvotes: 2

Related Questions