我有一个已经映射过的" data“对象,我需要映射cmsmenuschild,并将其放在"children:[]”,因为它也有对象的数据数组,我希望将cmsmenuschild有效负载id和name更改为键和标题,就像我之前对id和name所做的那样。我在React上非常新,所以我仍然在琢磨着如何在地图中(如this.any帮助)来绘制地图。
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"},
]
},
]发布于 2018-07-02 18:37:17
您只需在cmsmenuschild对象数组上映射,如下所示:
data.map((privilege) => {
return {
key: privilege.id,
title: privilege.name,
children: privilege.cmsmenuschild.map(child => {
return {keys: child.id, title: child.name}
}),
}
})发布于 2018-07-02 18:22:58
你不需要再地图了:
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;
});https://stackoverflow.com/questions/51141731
复制相似问题