我有两个状态,一个有类别,另一个有项目。
我所需要的是一个将两个状态结合起来的最终状态,要么将一个状态合并到另一个状态中,要么创建第三个状态。
类别状态如下所示:
{
category1: { items: [] },
category2: { items: [] }
}
第二个状态是一个项目数组,它看起来像这样:
[
{"id": "1", itemInfo: { name: "itemName", category: "category1" }},
{"id": "2", itemInfo: { name: "itemName", category: "category1" }},
{"id": "3", itemInfo: { name: "itemName", category: "category2" }},
{"id": "4", itemInfo: { name: "itemName", category: "category1" }},
{"id": "5", itemInfo: { name: "itemName", category: "category2" }},
{"id": "6", itemInfo: { name: "itemName", category: "category2" }}
]
我需要它是这样的:
{
category1: { items: [
{"id": "1", itemInfo: { name: "itemName", category: "category1" }},
{"id": "2", itemInfo: { name: "itemName", category: "category1" }},
{"id": "4", itemInfo: { name: "itemName", category: "category1" }}
]},
category2: { items: [
{"id": "3", itemInfo: { name: "itemName", category: "category2" }},
{"id": "5", itemInfo: { name: "itemName", category: "category2" }},
{"id": "6", itemInfo: { name: "itemName", category: "category2" }}
]}
}
请帮忙。
这是我尝试过的但没有效果的方法,它要么重复类别并最终得到 3 个“类别 1”和 3 个“类别 2”,要么新项目覆盖以前的项目。
const newFinalList = items.map((item: any) => {
return {[item.itemInfo.category]: {items: [item]}}
})
setFinalState((prevObj: any) => ({ ...prevObj, ...newFinalList }))