已知:两个数组
let list= [1, 21, 22, 3,31,412,43]
let admin= [
{
id: 1,
title: "首页",
},
{
id: 2,
title: "系统管理",
children: [
{
id: 21,
title: "个人信息",
},
{
id: 22,
title: "用户管理",
},
{
id: 23,
title: "权限配置",
}
]
},
{
id: 3,
title: "基础配置",
children: [
{
id: 31,
title: "数据字典",
}
]
},
{
id: 4,
title: "业务管理",
children: [
{
id: 41,
title: "采购管理",
children: [
{
id: 411,
title: "采购管理",
},
{
id: 412,
title: "采购预测",
}
]
},
{
id: 42,
title: "供应商管理",
},
{
id: 43,
title: "招标管理",
}
]
},
],
根据id循环想要得到:
let new = [
{
id: 1,
title: "首页",
},
{
id: 2,
title: "系统管理",
children: [
{
id: 21,
title: "个人信息",
},
{
id: 22,
title: "用户管理",
},
]
},
{
id: 3,
title: "基础配置",
children: [
{
id: 31,
title: "数据字典",
}
]
},
{
id: 4,
title: "业务管理",
children: [
{
id: 41,
title: "采购管理",
children: [
{
id: 412,
title: "采购预测",
}
]
},
{
id: 43,
title: "招标管理",
}
]
},
],
思路:树形结构筛选问题,一个节点要保留下来,则至少有一个后代元素中满足保留条件,或者它本身满足保留条件,这里的保留条件即节点id是否出现在给定数组中。
给个通用的递归版本吧, func描述节点保留条件,五六行代码够简单吧:
调用:
执行结果: