需求: 将级联多选框选择后得到的二维数组重新组成一个新的级联多选框, 级联多选框选择后得到的是一个二维数组, 需要转成树结构.
例如:
let arr = [
[100, 110, 111],
[100, 120, 129],
[100, 120, 169],
[500, 520, 521, 521.2],
[500, 550, 522]
]
前提: 二维数组的每一项第一个必须是顶节点, 后面每一个都是前一个的子节点, 例如[100,110,111] 中, 100是顶节点, 110的父节点是100, 111的父节点是110.
方法
function toTree(arr) {
let tree = []
arr.forEach((list) => {
search(list, tree)
})
return tree
function search(list, tree) {
if (list.length) {
//判断tree中是否有list[0], 有则返回下标, 没有则返回-1
let index = getIndex(list[0], tree)
if (index !== -1) {
//已有该节点,继续向下找
search(list.slice(1), tree[index].childList)
} else {
//没有该节点创建节点
tree.push(format(list))
}
}
}
function format(list) {
return list.length
? {
id: list[0],
childList: [format(list.slice(1))]
}
: []
}
function getIndex(id, list) {
for (let i in list) {
if (list[i].id === id) {
return i
}
}
return -1
}
}
结果:
toTree(arr)
// [
// ({
// id: 100,
// childList: [
// {
// id: 110,
// childList: [{ id: 111, childList: [] }]
// },
// {
// id: 120,
// childList: [
// { id: 129, childList: [] },
// { id: 169, childList: [] }
// ]
// }
// ]
// },
// {
// id: 500,
// childList: [
// {
// id: 520,
// childList: [
// {
// id: 521,
// childList: [{ id: 521.2, childList: [] }]
// }
// ]
// },
// {
// id: 550,
// childList: [{ id: 522, childList: [] }]
// }
// ]
// })
// ]
222

被折叠的 条评论
为什么被折叠?



