Stefan
Stefan

Reputation: 1895

Check if array exists in json Javascript/Jquery

I have a json file from the twitter api. Sometimes it does have the media[0] array and sometimes it doesnt. If it does i want to add the array to another array so it reminds it otherwise i want it to check the next one.

this is what i tried but it didnt work fine yet.

if(twitter.statuses[key].entities.media[0].media_url!=="Uncaught TypeError: Cannot read property '0' of undefined"){
    console.log(twitter.statuses[key].entities.media[0].media_url);
} 

It keeps giving the error: Uncaught TypeError: Cannot read property '0' of undefined if the media array doesnt exist otherwise it works fine and goes further.

Does someone know how to fix this?

Thanks for helping!

Upvotes: 0

Views: 641

Answers (3)

Jean-Karim Bockstael
Jean-Karim Bockstael

Reputation: 1405

An undefined property has the undefined type and value, you can check against it like this:

if (twitter.statuses[key].entities.media !== undefined) {
    // ...
}

or like this:

if (typeof twitter.statuses[key].entities.media !== "undefined") {
    // ...
}

Upvotes: 2

Alberto De Caro
Alberto De Caro

Reputation: 5213

I suggest you to always initialize variables to check null or undefined values. In your case:

var media0 = twitter.statuses[key].entities.media[0] || null;
if(media0 != null){
    if(media0.media_url != null)
       console.log(twitter.statuses[key].entities.media[0].media_url);
    else
       console.log('twitter.statuses[key].entities.media[0].media_url is null or not defined');
}
else
    console.log('twitter.statuses[key].entities.media[0] is null or not defined');

Upvotes: 0

leopik
leopik

Reputation: 2351

You're getting the error because you want to retrieve first element of ... nothing (twitter.statuses[key].entities.media[0]; media is already a null and you can't access first element of null)

Try checking with

if (typeof twitter.statuses[key].entities.media != "undefined") {
    ...

Upvotes: 2

Related Questions