0

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!

3 Answers 3

2

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") {
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this worked i kept trying this with media[0] instead of media thanks for the help
2

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

2 Comments

this doesnt work media[0] gives the same error as above but without the [0] it works fine thanks!
I shouldn't post answers before coffee… fixed.
0

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

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.