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

337
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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