skip to Main Content

Twitter API:
https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/introduction

In theory, when there is no data, it should leave the value as empty. As seen in this part of the script:

if (
  obj_data.data[int_i].entities.hasOwnProperty("urls") &&
  Array.isArray(obj_data.data[int_i].entities.urls) &&
  obj_data.data[int_i].entities.urls[0].expanded_url != undefined
  ) {
    array_Expanded_url.push([obj_data.data[int_i].entities.urls[0].expanded_url]);
  } else {
    array_Expanded_url.push([""]); 
  }

But this error alert appears:

TypeError: Cannot read property 'hasOwnProperty' of undefined

And the error appears obviously indicating this line:

  obj_data.data[int_i].entities.hasOwnProperty("urls") &&

How could I modify my script so that this doesn’t happen anymore?

2

Answers


  1. Just check the chain for truthy values

    if ( obj_data.data && obj_data.data[int_i] && obj_data.data[int_i].entities && obj_data.data[int_i].entities.urls &&
        Array.isArray(obj_data.data[int_i].entities.urls) &&
        obj_data.data[int_i].entities.urls[0].expanded_url != undefined) 
      { ....
    

    or the more concise (thank you @Scotty Jamison)

    if (obj_data.data?.[int_i]?.entities?.urls?.[0]?.expand_url !== undefined) {...
    

    and you can see where things are breaking down

    console.log(!obj_data.data, !obj_data.data[int_i], !obj_data.data[int_i].entities,  !obj_data.data[int_i].entities.urls);
    

    ex output:
    false false true true

    Login or Signup to reply.
  2. Check for null or undefined values

    if (
      obj_data?.data[int_i]?.entities?.hasOwnProperty('urls') &&
      Array.isArray(obj_data?.data[int_i]?.entities.urls) &&
      obj_data?.data[int_i]?.entities?.urls[0]?.expanded_url != undefined
    ) {
      array_Expanded_url.push([
        obj_data.data[int_i].entities.urls[0].expanded_url,
      ]);
    } else {
      array_Expanded_url.push(['']);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search