Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda