如何将扁平对象数组转换为具有层级嵌套的树状结构?
js数据整理
问题: 如何将给定数据结构(扁平对象数组)转换为具有层级嵌套的树状结构?
数据示例:
[ { "id": 1, "key": "", "name": "系统管理", "level": 1, "type": 1, "icon": "", "code": "a001", "parentcode": "", "num": "a-1", }, { "id": 7, "key": "", "name": "日志管理", "level": 1, "type": 1, "icon": "", "code": "a004", "parentcode": "", "num": "a-7", }, { "id": 8, "key": "roleadd", "name": "角色管理", "level": 2, "type": 1, "icon": "", "code": "b001", "parentcode": "a001", "num": "1-1", }, { "id": 14, "key": "logomanage", "name": "日志管理", "level": 2, "type": 1, "icon": null, "code": "e001", "parentcode": "a004", "num": "1-1", } ]
期望结果:
[ { "id": 1, "key": "", "name": "系统管理", "level": 1, "type": 1, "icon": "", "code": "a001", "parentcode": "", "num": "a-1", "children": [{ "id": 8, "key": "roleadd", "name": "角色管理", "level": 2, "type": 1, "icon": "", "code": "b001", "parentcode": "a001", "num": "1-1", }] }, { "id": 7, "key": "", "name": "日志管理", "level": 1, "type": 1, "icon": "", "code": "a004", "parentcode": "", "num": "a-7", "children": [{ "id": 14, "key": "logomanage", "name": "日志管理", "level": 2, "type": 1, "icon": null, "code": "e001", "parentcode": "a004", "num": "1-1", }] } ]
回答:
可以使用递归算法将扁平数据转换为树状结构。以下代码演示了如何实现:
let list = res[0]["__menus__"]; function transformData(data) { const result = []; for (const item of data) { const children = transformData( data.filter((d) => d.parentCode === item.code) ); if (children.length) { result.push({ ...item, children }); } else { result.push(item); } } return result; } console.log(transformData(list));
将给定的数据作为 res[0]['__menus__'] 传递给 transformdata 函数,该函数会递归循环数据,为具有相同父级代码的项目创建嵌套的树状结构。最终,函数返回一个具有层级嵌套的树状结构新数组,符合期望的结果。
以上就是如何将扁平对象数组转换为具有层级嵌套的树状结构?的详细内容,更多请关注其它相关文章!