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

340
Visualizações
Get a property of an object using forEach even though it doesn't exist

What I basically have is an array of objects with several properties, but not all of them have the same properties.

const data = [
      {
        car: 12,
        airplane: 42,
        peoples: 2,
      },
      {
        car: 12,
        peoples: 2,
      },
      {
        car: 12,
        airplane: 42,
        peoples: 2,
      },
    ];

What I want to do is apply a filter() to filter the objects with the condition below. The problem is that there are objects with these properties missing and consequently the code ends up breaking. What is the best way to do this without breaking the code?

data.forEach((item) => item.airplane > 5);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Using Array#filter:

const data = [ { car: 12, airplane: 42, peoples: 2 }, { car: 12, peoples: 2 }, { car: 12, airplane: 42, peoples: 2 } ];

const res = data.filter(({ airplane }) => airplane && airplane > 5);

console.log(res);

about 4 years ago · Juan Pablo Isaza Relatório

0

Your most succinct option here is to use optional chaining (?.) and the nullish coalescing operator (??) -- the combination of these two allow you to use some fallback option when some property in the chain is missing. So you would rewrite your callback as:

(item) => (item?.airplane ?? 0) > 5

In the case that item.airplane is defined, you will get the calculation as expected. If it is not, it will fallback to assessing 0 > 5.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to use filter() and you need to expand a little on your filter logic to check for the property -

const result = data.filter((item) => item.airplane && item.airplane > 5)
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