1

I am mapping an array of objects and rendering a div based on it.

Below is my code:

const App = () => {
    const types = React.useMemo(() => {
        return get(data, 'something.typesDetails', []);
    }, [data]);

    return (
        {true &&
            <div> header </div>
            <div>
                {types.map((t => {
                    return (
                        <div>{type.name}</div>
                    )
                })}
            </div>
        }
    );
}

Here is the types array:

const types = [
    {
        id: '1',
        name:  'type1',
    },
    { 
        id: '2',
        name: 'type2',
    },
]

The above code works fine when data structure is like above.

But consider if types has value like so

const types = [
    {
        id: null,
        name: null,
    }
]

In this case, it will still map through types and display div. I don't want to display div element. How can I check if types value contains null or stop looping through types if it has value like above?

2 Answers 2

2

You can use filter to remove elements with null values.

types = types.filter(x => !Object.values(x).includes(null));

You can also use Array#every to check:

if(types.every(x => !Object.values(x).includes(null)){
  //go ahead with mapping
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can filter object inside of array and then map through them:

return (
    {true &&
        <div> header </div>
        <div>
            {types.filter(t => t.id != null && t.name != null)
                  .map((t => {
                       return (<div>{type.name}</div>)
            })}
        </div>
    }
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.