Home > Software engineering >  Reset the id property of a JavaScript object
Reset the id property of a JavaScript object

Time:05-11

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?

CodePudding user response:

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

CodePudding user response:

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)

  • Related