/**
* 树转数组扁平化结构
* 深度优先遍历 堆栈 后进先出
* node 树数据
* keys 所有所包含的key
*/
export function deep(node, keys) {
let stack = node,
data = [];
while (stack.length != 0) {
let pop = stack.pop();
let tempObj = {}
keys.forEach(item => {
tempObj[item] = pop[item]
});
data.push(tempObj)
let children = pop.children
if (children) {
for (let i = children.length - 1; i >= 0; i--) {
stack.push(children[i])
}
}
}
return data
}
/**
* 数组转树 递归求解
* list 数组
* parId 顶级节点id
* pKey 父级节点key
*/
export function toTree(list, parId, pKey) {
let len = list.length
function loop(parId) {
let res = [];
for (let i = 0; i < len; i++) {
let item = list[i]
if (item[pKey] == parId) {
item.children = loop(item.id)
res.push(item)
}
}
return res
}
return loop(parId)
}
// 示例如下
/**
* let treeList2 = [
{
id: "123",
parentId: 0,
sectionId: 6,
label: 'a',
children: [
{
id: "1",
parentId: "123",
sectionId: 6,
label: 'b',
kmlfileUrl: "http://1.15.23.25/bim/kmlUrl/T6.kml",
children: []
},
{
id: "2",
parentId: "123",
sectionId: 2,
label: 'c',
kmlfileUrl: "http://1.15.23.25/bim/kmlUrl/T2.kml",
children: []
},
{
id: "3",
parentId: "123",
sectionId: 3,
label: 'd',
kmlfileUrl: "http://1.15.23.25/bim/kmlUrl/T3.kml",
children: []
},
{
id: "4",
parentId: "123",
sectionId: 4,
label: 'e',
kmlfileUrl: "http://1.15.23.25/bim/kmlUrl/T4.kml",
children: []
}
]
},
]
*/
// let list = deep(treeList2, ["id", "name", "label", "parentId", "kmlfileUrl"])
// let tree = toTree(list, "0")
js-树转数组,数组转树
于 2022-12-13 17:25:26 首次发布