简体   繁体   中英

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!

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") {
    ...

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") {
    // ...
}

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM