let res = [
{
"PLATFORM": "",
"MENUURL": "http://10.172.17.190:50001/root/sensitiveWord",
"MENUTITLE": "敏感词库1",
"MODULEID": "MGCK01",
"OPENMETHOD": "",
"PID": 1276,
"ID": 1304,
"USERROLEFUNMENU": []
},
{
"PLATFORM": "",
"MENUURL": "http://10.172.17.190:50001/root/homepage",
"MENUTITLE": "首页展示",
"MODULEID": "YJSY",
"OPENMETHOD": "",
"PID": 0,
"ID": 1271,
"USERROLEFUNMENU": []
},
{
"PLATFORM": "",
"MENUURL": "http://10.172.17.190:50001/root/alarmConfig",
"MENUTITLE": "预警配置",
"MODULEID": "YJPZ01",
"OPENMETHOD": "",
"PID": 1274,
"ID": 1275,
"USERROLEFUNMENU": []
},
{
"PLATFORM": "",
"MENUURL": "http://10.172.17.190:50001/root/alarmMake/#/History",
"MENUTITLE": "敏感词库2",
"MODULEID": "MGCK02",
"OPENMETHOD": "",
"PID": 1276,
"ID": 1305,
"USERROLEFUNMENU": []
},
{
"PLATFORM": "全平台",
"MENUURL": "http://10.172.17.190:50001/root/alarmMake/#/Make",
"MENUTITLE": "预警制作",
"MODULEID": "YJZZ001",
"OPENMETHOD": "",
"PID": 0,
"ID": 68,
"USERROLEFUNMENU": []
},
{
"PLATFORM": "",
"MENUURL": "http://10.172.17.190:50001/root/sensitiveWord/#/",
"MENUTITLE": "敏感词库",
"MODULEID": "MGCK",
"OPENMETHOD": "",
"PID": 1274,
"ID": 1276,
"USERROLEFUNMENU": []
},
{
"PLATFORM": "",
"MENUURL": "http://10.172.17.190:50001/root/alarmMake/#/Notice",
"MENUTITLE": "通知制作",
"MODULEID": "TZZZ",
"OPENMETHOD": "",
"PID": 0,
"ID": 1273,
"USERROLEFUNMENU": []
},
{
"PLATFORM": "",
"MENUURL": "http://10.172.17.190:50001/root/autoPublish/",
"MENUTITLE": "自动发布渠道",
"MODULEID": "ZDFBQD",
"OPENMETHOD": "",
"PID": 1274,
"ID": 1277,
"USERROLEFUNMENU": []
},
{
"PLATFORM": "",
"MENUURL": "http://10.172.17.190:50001/root/alarmConfig",
"MENUTITLE": "预警配置",
"MODULEID": "YJPZ",
"OPENMETHOD": "",
"PID": 0,
"ID": 1274,
"USERROLEFUNMENU": []
},
{
"PLATFORM": "",
"MENUURL": "http://10.172.17.190:50001/root/alarmMake/#/History",
"MENUTITLE": "NIFS错误库",
"MODULEID": "NIFS",
"OPENMETHOD": "",
"PID": 1274,
"ID": 1278,
"USERROLEFUNMENU": []
}
]
function toTree(nodes) {
let result = []
//如果值是 Array,则为true; 否则为false。
if (!Array.isArray(nodes)) {
return result
}
//深拷贝,否则会影响原数组
let node = JSON.parse(JSON.stringify(nodes))
//根据父节点进行拼接子节点,
node.forEach(item => delete item.children)//已经有的话就删掉
//把每一项的引用放入map对象里
let map = {}
node.forEach(item => map[item.ID] = item)
let newNode = []
node.forEach(dt => {
let parents = map[dt.PID]
if (parents) {
//如果 map[dt.pid] 有值 则 parents 为 dt 的父级
//判断 parents 里有无child 如果没有则创建 如果有则直接把 dt push到child里
((parents.children) || (parents.children = [])).push(dt)
//等同于:
// if (!parents.child) {
// parents.child = []
// }
// (parents.child).push(dt)
} else {
newNode.push(dt)
}
})
return newNode
}
console.log(toTree(res))
console