javascriptgoogle-apps-scriptgoogle-sheetstwitterhasownproperty

TypeError: Cannot read property 'hasOwnProperty' of undefined - Twitter API V2 vs. GAS


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?


Solution

  • 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