Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter undefined value in javascript arrays?

Tags:

javascript

const values = dataSku.map(sku => {return map.skuInfo[sku].description})

Here, there is some posibility that map.skuInfo[sku] can be null/undefined and I need to filter it. How would it be possible ?

like image 348
Tanvi Jaywant Avatar asked May 23 '18 20:05

Tanvi Jaywant


2 Answers

Sounds like you want .filter. It's a higher order function like .map.

const values = dataSku
    .filter(item => item.description !== undefined)

I'm not sure your exact data structure but check it out here! It filters out all non-truthy return values.

like image 196
Tom Con Avatar answered Oct 10 '22 07:10

Tom Con


This will solve your problem -

const values = dataSku.map(sku => map.skuInfo[sku]}).filter(skuInfo => typeof skuInfo !== "undefined").map(skuInfo => skuInfo.description);
like image 22
Vivek Avatar answered Oct 10 '22 09:10

Vivek