0

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.

3
  • filter null values away? Commented Sep 26, 2016 at 13:11
  • do not use map in that way, it's just igrones your condition stackoverflow.com/questions/26716818/… Commented Sep 26, 2016 at 13:12
  • @EmilS.Jørgensen Just give me the links only. Commented Sep 26, 2016 at 13:12

2 Answers 2

3

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.

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

3 Comments

This method is returning objects, I only need the string urls.
You need to chain .map to it like Emil used. .map(obj => obj.image_url) and you're good.
@SterlingArcher Nice, short and to the point. Carefull with const and Lambda functions though if compatibility is an issue.
2

var data = [
  {
    url: null
  },
  {
    url: null
  },
  {
    url: '123'
  },
  {
    url: null
  }
]
console.log(
  data.filter(function (a) {
    return a.url != null
  }).map(function (a) {
    return a.url
  })
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.