普通数组转树形结构
function toTree (data) {
const arr = JSON.parse(JSON.stringify(data))
let obj = {}
let list = []
arr.forEach(el => obj[el.id] = el)
arr.forEach((el) => {
let parent = obj[el.pid]
if (parent) {
parent.children ? parent.children.push(el) : parent.children = [el]
} else {
list.push(el)
}
})
return list
}
数形结构查找id
function find (data, id) {
let tem = null
let isFind = false
function fn (data) {
if (Array.isArray(data) && !isFind) {
data.forEach((el) => {
if (el.id === id) {
tem = el
isFind = true
} else {
if (el.children) {
fn(el.children)
}
}
})
}
}
fn(data, id)
return tem
}
树结构根据子id查找所有父级id
function find (data, id) {
let tem = []
function fn (arr, id) {
for (let i = 0; i < arr.length; i++) {
let item = arr[i]
if (item.id === id) {
tem.push(item.id)
fn(data, item.pid)
break
} else {
if (item.children) {
fn(item.children, id)
}
}
}
}
fn(data, id)
return tem.reverse()
}
网友评论