英文:
Angular update an object in an array with new values, inside a reducer
问题
基本上,我有一个类别对象数组,其中对象的结构如下 { "categoryId": 10, "categoryName": "beverages", "description": "drinkable liquids" },在我修改类别的最后两个属性中的任何一个信息后,我希望能够更新数据。
我的代码如下:
const reducer = createReducer(
initialCategoriesState,
on(categoriesActions.updateCategory, (state, { data }) => ({
...state,
categories: state.categories?.map((item) => (item['categoryId'] === data['categoryId'] ? data : item)),
}))
);
但它不会更新我想要的类别,而是创建一个新的类别,其中包含本应属于需要更新的类别的新细节。
英文:
Basically, I have an array of categories objects, where an object looks like this {"categoryId":10, "categoryName":"beverages", "description": "drinkable liquids"} and after I modify the information in any of the last two attributes of the category, I want to be able update the data.
My code is:
const reducer = createReducer(
initialCategoriesState,
on(categoriesActions.updateCategory, (state, {data }) => ({
...state
categories: state.categories?.map((item) => (item['categoryId'] === data['categoryId'] ? data:item)),
}))
But it doesn't update the category that I want, it just creates a new category with the new details that were supposed to belong to the category that I must be updated
答案1
得分: 0
你可以使用对象展开语法来合并两个对象:
state.categories?.map(item => item.categoryId === data.categoryId ? {...item, ...data} : item)
英文:
You can use object spread syntax to combine two objects:
state.categories?.map(item => item.categoryId === data.categoryId ? {...item, ...data} : item)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论