我有两个数据,一个是对象数组,第二个是映射对象。所以我试图实现这样的逻辑,即我的第一个对象及其数组的 subarr 对象具有键值 id:1
然后,匹配 1 可用作花药映射对象中的键.那我该如何解决呢?
数据1(对象数组)
[
{
"id": 1,
"title": "Dashboard",
"route": "Dashboard",
"routeid": 1,
"key": "dashboard",
"icon": "home",
"subarr": []
},
{
"id": 2,
"title": "Pages",
"route": "Pages",
"routeid": 2,
"key": "pages",
"icon": "diamond",
"subarr": [
{
"id": 3,
"title": "Tabs",
"route": "Tabs",
"key": "tab",
"routeid": 3,
"icon": "grid"
},
{
"id": 4,
"route": "Test",
"key": "test",
"icon": "adn",
"routeid": 4,
"title": "Test"
}
]
},
{
"id": 5,
"title": "Components",
"key": "Components",
"route": "component",
"routeid": 5,
"icon": "notebook",
"subarr": [
{
"id": 6,
"route": "Card",
"key": "card",
"icon": "i-card",
"routeid": 6,
"title": "Card"
},
{
"id": 7,
"title": "Button",
"route": "Button",
"routeid": 7,
"key": "button",
"icon": "control-play"
},
{
"id": 8,
"title": "Table",
"route": "Table",
"key": "table",
"routeid": 8,
"icon": "list"
},
{
"id": 9,
"title": "Charts",
"route": "Chart",
"routeid": 9,
"key": "chart",
"icon": "chart"
}
]
},
{
"id": 10,
"title": "notifications",
"route": "User",
"key": "user",
"routeid": 10,
"icon": "bell",
"subarr": []
},
{
"id": 11,
"title": "User profile",
"route": "Profile",
"routeid": 11,
"key": "profile",
"icon": "user",
"subarr": []
},
{
"id": 12,
"title": "Carousel",
"route": "Carousel",
"key": "carousel",
"routeid": 12,
"icon": "layers",
"subarr": []
}
]
映射对象:
{
"1": "dashboard",
"2": "pages",
"3": "tab",
"4": "test",
"6": "card",
"7": "button",
"8": "table",
"9": "chart",
"10": "user",
"11": "profile",
"12": "carousel"
}
答案 0 :(得分:1)
let exists = [];
data1.map((el, id) => {
if (Object.keys(mapping).includes(el.id.toString()))
exists = [...exists, { id: el.id, exists: true }];
else exists = [...exists, { id: el.id, exists: false }];
el.subarr.map((l, i) => {
if (Object.keys(mapping).includes(l.id.toString()))
exists = [...exists, { id: l.id, exists: true }];
else exists = [...exists, { id: l.id, exists: false }];
});
});
exists
数组将包含 id 和每个 id 的状态,即它们是否存在于映射对象中