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

235
Visualizações
Reset the id property of a JavaScript object

I have an array of objects like this

const initialState = [
  {
    id: 1, author: 'author 1', title: 'Book 1', category: 'Category 1',
  },
  {
    id: 2, author: 'author 2', title: 'Book 2', category: 'Category 2',
  },
  {
    id: 3, author: 'author 3', title: 'Book 3', category: 'Category 3',
  },
];

if one object is removed, for example; the object with id of 2 is removed. I want to reset the id properties of the remaining properties so they follow an order of 1, 2, 3...

I have done this with;

let id = 1
state.forEach(object => {
  object.id = id
  id += 1
})

Is there a much better way to do this? like using the map function?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your code can be improved just by using the index

state.forEach((object, index) => {
  object.id = index + 1
})

You can also use map function as you suggested but it will return a new array

const newArray = state.map((object, index) => {
  object.id = index + 1
})
about 4 years ago · Juan Pablo Isaza Relatório

0

If you want to follow immutable practices (if that's what you mean by better), you can use the spread operator (or Object.assign):

const initialState = [
  {
    id: 1, author: 'author 1', title: 'Book 1', category: 'Category 1',
  },
  // commented out for demonstration: this element would be "removed".
  //{
    //id: 2, author: 'author 2', title: 'Book 2', category: 'Category 2',
  //},c
  {
    id: 3, author: 'author 3', title: 'Book 3', category: 'Category 3',
  },
];

const newState = initialState.map((obj, i) => ({ ...obj, id: i + 1 }));

console.log(initialState)
console.log(newState)

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