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

230
Vistas
Iterate an value in the object and Filter them if is not null

So I want to iterate some users, and each of those users has an object name vehicles and I want to iterate the users, and also then iterate the vehicles value within the object, but the problem is that the second iteration that iterates the vehicles sometimes gives an error because a user might have null users, and it doesn't iterate them and stops the loop by giving an error, what I want to do is, skip the iteration on that value if it is null.

Here is my code:

const c = clients.clients.filter((c) => 
  c.vehicles.map((v) => console.log(v._id))
);

Error message: Uncaught TypeError: Cannot read properties of null (reading 'map')

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Take a look at the optional chaining operator ?.

In your case, the loop would become

const c = clients.clients.filter(c => 
  c.vehicles?.map(v => console.log(v._id));
);

To give a brief explanation of the operator, when used on a property that might not be present (I'm assuming vehicles in your case), instead of raising an error it short-circuits the evaluation to undefined, which is a falsy value, and it is therefore filtered out by .filter.

about 4 years ago · Juan Pablo Isaza Denunciar

0

try this :

const c = clients.clients.filter((c) => {
  if(!c) return false;
  if(!c.vehicles) return false;
  return c.vehicles.map((v) => console.log(v._id))
  }
);
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