«
循环 tree结构数组

时间:2022-11-18    作者:熊永生    分类: js


循环 tree结构数组 注意异步方法

方法

// 数组转换
const flatten = async (list, childName, func, isOnlyLeaf) => {
list.forEach((item) => {
if (item[childName] && item[childName].length > 0) {
flatten(item[childName], childName, func, isOnlyLeaf);
if (!isOnlyLeaf) {
for (let keys in item) {
func(item)
}
return
}
} else {
for (let keys in item) {
func(item)
}
return
}
})
return list;
}

调用

let arr = await flatten(list,'children',(item)=>{
item.key = item.id, 
item.title = item.name,
})