我有一个已经映射过的“数据” 对象,我需要映射 cmsmenuschild 并将其放在“ children:[]” ,因为它也具有对象的数据数组,因此我想将 cmsmenuschild 有效负载 id 和 name 更改为 key 和 title ,就像我之前对id和name所做的一样。 我真的是React的新手,所以我仍然想弄清楚如何在这样的地图中制作地图。任何帮助将不胜感激
constructor(props) {
super(props);
this.state = {
listMenu: []
};
}
data = [
{
"id": 1,
"name": "Manage User",
"cmsmenuschild": [
{"id": 14,"name": "Create User"},
{"id": 15,"name": "Update User"},
]
},
{
"id": 2,
"name": "Manage BTP",
"cmsmenuschild": [
{"id": 18,"name": "Create BTP"},
{"id": 19,"name": "Update BTP"},
]
},
]
const privilegesData = this.data.map((privilege) => {
return {
key: privilege.id,
title: privilege.name,
children:[{
key: privilege2.id,
title: privilege2.name,
}],
};
});
this.setState({
listMenu: privilegesData,
});
预期将显示新的this.state.listMenu,就像这样
this.state.listMenu : [
{
"key": 1,
"title": "Manage User",
"children": [
{"key": 14,"title": "Create User"},
{"key": 15,"title": "Update User"},
]
},
{
"key": 2,
"key": "Manage BTP",
"children": [
{"key": 18,"title": "Create BTP"},
{"key": 19,"title": "Update BTP"},
]
},
]
答案 0 :(得分:3)
您无需再次映射:
const privilegesData = this.data.map((privilege) => {
return {
key: privilege.id,
title: privilege.name,
children: privilege.cmsmenuchild, // or [...privilege.cmsmenuchild] if your worried about mutability
};
});
编辑:如果您需要处理具有任意数量的子代的递归数据结构
const keyAndTitle = (obj) => ({ key: o.id, title: o.name });
const normalizeObj = (data) => data.map(d => {
const obj = keyAndTitle(data);
if (d.hasOwnProperty('cmsmenuchild')) {
obj.children = normalizeObj(d.cmsmenuchild);
}
return obj;
});
答案 1 :(得分:2)
您可以像这样在cmsmenuschild
对象数组上进行映射:
data.map((privilege) => {
return {
key: privilege.id,
title: privilege.name,
children: privilege.cmsmenuschild.map(child => {
return {keys: child.id, title: child.name}
}),
}
})