1

So I'm iterating an array with objects and checking for a specific id, and this works fine when It has an id, but some time that is null and when it is it throws an error can't read properties of null or something similar.

Here is my function, and I would like to check the case, if it is null then just skip and don't iterate that object so I can avoid that error:

Here is the function:

const d = vehicles.vehicles.filter((vehicle) => vehicle.owner._id === quick.temp.customer._id);
0

1 Answer 1

3

You can add a simple check if variable is an object:

const d = vehicles.vehicles.filter((vehicle) => vehicle && vehicle.owner && vehicle.owner._id === quick.temp.customer._id);

This might fail if vehicle.owner is anything non-null and not an object, but you can further expand it to check the type vehicle.owner instanceof Object

With ES6 you can use optional chaining: ?

const d = vehicles.vehicles.filter((vehicle) => vehicle?.owner?._id === quick.temp.customer._id);

It's a little slower though.

And finally you can wrap the condition into try{}catch(e){} than you don't have to worry about errors:

const d = vehicles.vehicles.filter((vehicle) =>
{
  try
  {
    return vehicle.owner._id === quick.temp.customer._id
  }
  catch(er){}
});

This method is the slowest of them all https://jsbench.me/zzl1871t5u/1

Sign up to request clarification or add additional context in comments.

1 Comment

And how can you do that, I mean to check the owner one because its the same I think

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.