• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
四品带砖侍卫
博客园    首页    新随笔    联系   管理    订阅  订阅

请封装⼀个⽅法,将以下树形数据转换成期望的格式

转化前
const list = [
{id:1},
{pid:1,id:2},
{id:3},
{pid:3,id:4},
{pid:4,id:5}
]
转化后
[{
id:1,
children:[{
pid:1,
id:2
}]
},
{
id:3,
children:[{
pid:3,
id:4,
children:[{
pid:4,
id:5
}]
}]
}]
getChildren(arr, id) {
const res = [];//根据数据⼀致性,定义返回的结果
if (!id) { //如果没有传⼊id代表查找第⼀层数据
res.push(...arr.filter((item) => !item.pid));
} else {//传⼊id时,代表查找⼦节点
res.push(...arr.filter((item) => item.pid === id));
}
res.forEach((item) => {//查找后要递归每个节点,从⽽实现children属性
const children = getChildren(arr, item.id)
if (children.length) {//如果查找不到就不⽤赋值了,否则会多⼀个空数组
item.children = children;
}
});
return res;
}
//调⽤执⾏,list是转换前的数组,返回值是转换后的数组
getChildren(list)
posted @ 2023-04-12 09:02  四品带砖侍卫  阅读(18)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3