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

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

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

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