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

244
Vistas
How to handle the case if item is undefined?

In an array of objects I am trying to create a new property based on another array of numbers.
The problem is that the number of array has one less element, therefore it gets undefined in the last index of array of objects.
How to handle that case, if the new created property is undefined? See the code example below

const sortArr = [3, 2, 1];

const items= [
  {
    a: 1,
  },
  {
    a: 2,
  },
  {
    a: 3,
  },
  {
    a: 4,
  },
];

const res =
items.map((item, idx) => ({
    ...item,
      sortItem:sortArr[idx]
  }));
  
  console.log(res)

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

if it's the last in the array then show nothing/empty string

To use an empty string as fallback if sortArr[inx] does not exist, use the Nullish coalescing operator (??) operator:

sortItem: sortArr[idx] ?? ''

const sortArr = [3, 2, 1];
const items= [{a: 1, }, {a: 2, }, {a: 3, }, {a: 4, }, ];

const res = items.map((item, idx) => (
    {
        ...item,
        sortItem: sortArr[idx] ?? ''
    }
));

console.log(res)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can set sortItem based on whether idx is less than sortArr.length

sortItem: idx < sortArr.length ? sortArr[idx] : "no element at that position"

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