Ko7
Ko7

Reputation: 127

How to prevent map function from returning null

I have a list of objects called languages. If language object have alpha2 it should return { label: i.name, value: i.alpha2 } . If it does't have alpha2 it should return null .

languages.all.map((i,index) =>  i.alpha2 ? { label: i.name, value: i.alpha2 } : null )

But if I pass this to my react component, I got an error undefined is not an object. So I don't want pass null to array created by language.all.map I want to skip the process of passing something in the array.

How I can do this ?

Upvotes: 2

Views: 5871

Answers (1)

Mamun
Mamun

Reputation: 68933

As map returns results for every element in the calling array, you can filter null:

languages.all.map((i,index) =>  i.alpha2 ? { label: i.name, value: i.alpha2 } : null )
             .filter(i => i);

OR: Even better with reduce() in a single iteration

languages.all.reduce(function(acc, cur) {
  if (cur.alpha2) {
    var o = { label: cur.name, value: cur.alpha2 };
    acc.push(o);
  }
  return acc;
}, []);

Upvotes: 6

Related Questions