dantegr
dantegr

Reputation: 23

lodash orderBy issues when trying to make it case insensitive

I've written this orderBy condition to short an object array and it works fine unless the value that I am trying to sort is null. Below you can see my code:

if (this.state.sortType === 'name asc'){
  medias = _.orderBy(medias,[media  => _.get(media,'metadata.title').toString().toLowerCase() ] , 'asc')
} else if (this.state.sortType === 'name desc'){
  medias = _.orderBy(medias, [media  => _.get(media,'metadata.title').toString().toLowerCase()], 'desc')
}

When media.metadata.title is null it throws that error:

Cannot read property 'toString' of undefined

Any ideas?

Upvotes: 2

Views: 713

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

Why not take a default value of _.get, like an empty string in case metadata is not present in media object.

_.get(object, path, [defaultValue])
_.get(media,'metadata.title', '').toString()

Upvotes: 1

Related Questions