Reputation: 127
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
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