/**
* 树转数组
* @param tree
* @param hasChildren
*/
export function treeToList(tree = [], hasChildren = false) {
let queen = []
const out = []
queen = queen.concat(JSON.parse(JSON.stringify(tree)));
while (queen.length) {
const first = queen.shift()
if (first?.children) {
queen = queen.concat(first.children)
if (!hasChildren) delete first.children
}
out.push(first)
}
return out
}
/**
* 数组转树
* @param list
* @param tree
* @param superCode
* @param key
*/
export function listToTree(list = [], tree = [], dataCode = 0, currKey, key) {
list.forEach((item,index) => {
if (item[key] == dataCode) {
const child = {
...item,
children: []
}
listToTree(list, child.children,item[currKey], currKey,key)
if (!child.children?.length) delete child.children;
tree.push(child)
}
})
return tree
}
js 数组转树,树转数组
最新推荐文章于 2024-06-22 15:10:18 发布