重置JavaScript对象的id属性



我有一个像这样的对象数组

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',
},
];

如果一个对象被删除,例如;删除id为2的对象。我想重置其余属性的id属性,使它们遵循1、2、3…的顺序

我已经用;

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

有更好的方法吗?喜欢使用地图功能吗?

您的代码可以通过使用索引

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

你也可以使用map函数,但它会返回一个新的数组

const newArray = state.map((object, index) => {
object.id = index + 1
})

如果您希望遵循不可变实践(如果这就是您所说的更好),您可以使用扩展操作符(或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)

最新更新