degenPenguin
degenPenguin

Reputation: 725

Javascript .filter() -> cannot read property 'X' of null

is there a better way to write this line?

var tracks = responseJSON.items.map((item) => item.track).filter((item) => item.preview_url != null)

I often get this error: "TypeError: Cannot read property 'preview_url' of null"

I imagine it occurs because .map() returned an empty array, but if that were the case, wouldn't filter() merely do the same?

Upvotes: 0

Views: 215

Answers (2)

Fraser
Fraser

Reputation: 17094

Just test that item and item.preview_url are not null.

var tracks = responseJSON.items.map(item => item.track).filter(item => item != null && item.preview_url != null)

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370979

Sounds like the track is sometimes null, so filter out items with no tracks before trying to access a property of it, which can be done concisely with optional chaining:

const tracks = responseJSON.items
  .map(item => item.track)
  .filter(item => item?.preview_url != null);

Or:

const tracks = responseJSON.items
  .map(item => item.track)
  .filter(item => item && item.preview_url != null);

Upvotes: 4

Related Questions