扁平化操作:https://blog.csdn.net/weixin_44523860/article/details/122542852
扁平处理后的路由path与原路由进行匹配,得到选中的路由
(结合树形控件的叶子)
//扁平处理后的路由数组
let res = ['1<1.1<1.1.1', '2<2.1<2.1.1', '2<2.2', '3<3.1'] //原路由
let arr = [
{
id: '1',
children: [
{
id: '1<1.1',
children: [{ id: '1<1.1<1.1.1' }, { id: '1<1.1<1.1.2' }],
},
{ id: '1<1.2' },
],
},
{
id: '2',
children: [
{
id: '2<2.1',
children: [{ id: '2<2.1<2.1.1' }, { id: '2<2.1<2.1.2' }],
},
{ id: '2<2.2' },
],
},
{ id: '3', children: [{ id: '3<3.1' }, { id: '3<3.2' }] },
{ id: '4', children: [{ id: '4<4.1' }] },
]
// 输出结果:包含半选中的根,去除不需要的子节点
// ps: 由于处理时加了flag标记,可以自行删除
// let arr = [
// {
// id: '1',
// flag: true,
// children: [
// {
// id: '1<1.1',
// flag: true,
// children: [{ id: '1<1.1<1.1.1' }],
// },
// ],
// },
// {
// id: '2',
// flag: true,
// children: [
// {
// id: '2<2.1',
// flag: true,
// children: [{ id: '2<2.1<2.1.1' }],
// },
// { id: '2<2.2' },
// ],
// },
// { id: '3', flag: true, children: [{ id: '3<3.1' }] },
// ]
fun(arr, res)
function fun(arr, res) {
let myres = []
res.forEach((item) => {
let tmp = item.split('<')
for (let i = 1; i < tmp.length; i++) {
tmp[i] = tmp[i - 1] + '<' + tmp[i]
}
console.log(tmp)
myres.push(...tmp) //先不分层级,TODO可优化
})
console.log(myres)
// [
// [ '1', '1<1.1', '1<1.1<1.1.1' ],
// [ '2', '2<2.1', '2<2.1<2.1.1' ],
// [ '2', '2<2.2' ],
// [ '3', '3<3.1' ]
// ]
funsub(arr, myres)
let arr2 = JSON.parse(JSON.stringify(arr))
filterFlagRouter(arr2)
console.log(arr2)
}
function funsub(arr, myres) {
arr.forEach((item) => {
myres.forEach((id) => {
if (item.id === id) {
item.flag = true
}
if (item.children) {
funsub(item.children, myres)
}
})
})
}
function filterFlagRouter(arr) {
for (let i = 0; i < arr.length; i++) {
if (!arr[i].flag) {
arr.splice(i, 1)
i--
} else if (arr[i].children) {
filterFlagRouter(arr[i].children)
}
}
}