Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

42
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')

7 months 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.

7 months 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))
  }
);
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos