Amr Rady
Amr Rady

Reputation: 1197

How to solve TypeError: Cannot read property 'filter' of undefined error after replacing lodash find function with native JS filter function?

I'm trying to remove lodash find function, so my change is basically replacing this line:

const current = find(items, elem => elem.id === item.id);

with this one:

const current = items ? items.filter(function(x) {
  return x.id === item.id;
}) : null;

But I'm getting this error:

app.js:659 Uncaught (in promise) TypeError: Cannot read property 'filter' of undefined

Upvotes: 0

Views: 689

Answers (2)

mgarcia
mgarcia

Reputation: 6325

The filter method returns an array. If you want to use that method, you will have to select the first element of the returned array in order to have the same behaviour that lodash find method has:

const current = items.filter(x => x.id === item.id)[0];

That being said, it is simpler to use the find method of array:

const current = items.find(x => x.id === item.id);

If you opt for this second option, have in mind that find is not supported in Internet Explorer.

Upvotes: 0

Amr Rady
Amr Rady

Reputation: 1197

I don't know why filter is not working but this line solved the problem

    const current         = items.find(x => x.id === item.id);

Upvotes: 1

Related Questions