Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
Iterate an array and check objects with filter and skip the null values

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);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!