Sylar Sylar - 2 months ago 8
Javascript Question

Do not return null values in loop

How to return only the

image_url
when few
image_url
maybe
null
?

var lineItems = [
{
description: "Packaging",
image_url: null,
...
},
{
description: "T-Shirt",
image_url: <the-url-link>,
...
}
]


In react:

...

lineItems.map(function(line){
if (line.description !== "Packaging") {
var img = line.image_url;
}
console.log(img);
});

...


I keep getting
null
along with the web links in the console. How to grab only the
image_url
that has the links. "Packaging" will never have an image_url link; it'll always be
null
.

Answer

You can simply use a filter here to do that for you.

const nonNulls = lineItems.filter(item => item.image_url !== null);

This will filter out all the non-null values into a variable.

Comments