Home > Blockchain >  Iterate an array and check objects with filter and skip the null values
Iterate an array and check objects with filter and skip the null values

Time:03-27

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);

CodePudding user response:

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

  • Related