登录
首页 >  文章 >  前端

如何将扁平对象数组转换为具有层级嵌套的树状结构?

时间:2024-11-15 21:22:08 340浏览 收藏

小伙伴们对文章编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《如何将扁平对象数组转换为具有层级嵌套的树状结构?》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

如何将扁平对象数组转换为具有层级嵌套的树状结构?

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 函数,该函数会递归循环数据,为具有相同父级代码的项目创建嵌套的树状结构。最终,函数返回一个具有层级嵌套的树状结构新数组,符合期望的结果。

今天关于《如何将扁平对象数组转换为具有层级嵌套的树状结构?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>