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

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

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 Denunciar

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