-1

I have react native Loop to fill the select Items like below

   const categorylist = arr.map((data, key) => {
      if (data != "") {
        return <Select.Item label={data} value={data} key={data} />;
      }
    });

I loop and use it like below , it works fine when array contains non empty values, but when there is empty values i get the error

TypeError: null is not an object (evaluating 'child.props')

   <Select>
     {categorylist2}
    </Select>

How do i send only non empty array items using map. please note i don't want arr to be affected as i need it unchanged in other functions.

1
  • you can also use reduce instead of map and filter. Commented Apr 20, 2022 at 16:06

4 Answers 4

2

filter out the empty elements then map over the array filter returns.

Here's a contrived example to show you how it works.

const arr = [undefined, 'Bob', '', 'Sally', 'Joe', '', null, 'Pam'];

// `filter` out the empty/null/undefined elements
// and then `map` over that filtered array
const out = arr
  .filter(el => el)
  .map(el => `<div>${el}</div>`);

document.body.innerHTML = out.join('');

Sign up to request clarification or add additional context in comments.

Comments

0

You need to map through the array only if the array is not empty and use filter(Boolean) to filter out empty ones.

const newArr = arr.filter(Boolean);
const categorylist = (newArr.length > 0) && newArr.map((data, key) => {
    return <Select.Item label={data} value={data} key={data} />;
});

Comments

0

It is because in your map you do not return anything for empty values, which means null that's why you have the error. A map function should always return something.

Use filter before map like so:

arr.filter(data => data !== "").map(data => <Select.Item label={data} value={data} key={data} />)

Comments

0

It can be achieved by reducer function.

Using Array.filter() then Array.map() traverses the array twice, but you can achieve the same effect while traversing only once with Array.reduce(), thereby being more efficient.

More about it here

const categorylist = arr.reduce((acc, current, index) => {
      if (current != "") {
        acc.push(<Select.Item label={current} value={current} key={current} />);
      }
      return acc;
    }, []);
    
    console.log(categorylist);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.