sur sur - 1 month ago 5x
JSON Question

TypeError with JSON data in ionic2

i have a question on how to avoid errors in typescript, when filtering a particular variable in JSON data.
part of my JSON data will look like:

With contents of multimedia:

"per_facet": [],
"geo_facet": [],
"multimedia": [
"url": "",
"format": "Standard Thumbnail"
"url": "",
"format": "thumbLarge",

another element without the multimedia content:

"per_facet": [],
"geo_facet": [],
"multimedia": [],

So as you could see, "multimedia" variable on the array has a internal values on one of the element in array and in other it is not.

This is how i try to retrieve that parameter(which is a image).

<img [src]= "item.multimedia[0].url" *ngIf="item.multimedia[0].url.indexOf('http') === 0">

When i try to read the url parameter of the multimedia array,
it results in error ERR:"Cannot read URL of undefined". (Which is completely understandable since there is no data to show.)
This works for Javascript. I dono how to solve this.

how to avoid this error and retrieve other parameters from this array successfully.

Thanks in advance.


Instead of trying to access the field directly, try checking that it has that item first.

You could do

item.multimedia[0] && item.multimedia[0].url.indexOf('http') === 0


item.multimedia.length > 0 && item.multimedia[0].url.indexOf('http') === 0

I can't see your whole code so I could be wrong, but typically I'd recommend doing something that doesn't involve individual indexing, which can be very fragile.