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

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

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