Digital Farmer
Digital Farmer

Reputation: 2107

TypeError: Cannot read property '0' of undefined (Google App Script)

Error:

TypeError: Cannot read property '0' of undefined (line 59)

Here is the script where such an error appears:

Line 59        if (obj_data.data[int_i].entities.urls[0].expanded_url != undefined){
Line 60          array_Expanded_url.push([obj_data.data[int_i].entities.urls[0].expanded_url]);
Line 61        } else {
Line 62         array_Expanded_url.push([""]); 
Line 63        }

The idea of if was exactly when the value was undefined, it would define in else the empty value, but this is not happening. Are there any errors in the script visibly that I can't see?

Upvotes: 1

Views: 111

Answers (1)

Tanaike
Tanaike

Reputation: 201368

From your error message, I thought that in that situation, urls of obj_data.data[int_i].entities.urls might not be included. So in order to avoid this, how about the following modification?

Modified 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([""]); 
}

Upvotes: 1

Related Questions