Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda