1

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?

Digital Farmer
  • 1,705
  • 5
  • 17
  • 67

2 Answers2

2

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

Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • 2
    You can also simplify that with the newer "?." operator: obj_data.data?.[int_i]?.entities?.urls?.[0]?.expand_url !== undefined – Scotty Jamison Jun 23 '21 at 17:23
  • 1
    Thank you @ScottyJamison! I learned something new and added to my answer. – Kinglish Jun 23 '21 at 17:27
  • Hi @Kinglish , the most concise mode unfortunately doesn't work because it ends up leaving all lines null, when in fact what is needed is to leave only the line where it is. But according to ```Ranjith S``` answer I was able to understand your idea and end up joining the two answers to use in my script. Both answers are correct, but you answered first so it deserves to be verified as the best answer. – Digital Farmer Jun 23 '21 at 17:45
1

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(['']);
}
Ranjith S
  • 205
  • 1
  • 5