扁平化递归查询树中某一个节点及当前节点及以下的所有节点
var arr = [{name: 1, children: [{name: 2, children: [{name: 3, children: []}]}]}]
let arrs = dgtest(arr[0])
function dgtest(root) {
let arr = []
if (root.children.length) {
arr = root.children.flatMap(child=>{dgtest(child)})
}
return [root, ...arr]
}
d第二种 去掉了children
let tree = [ { "id": 1, "name": "1", "pid": 0, "children": [ { "id": 2, "name": "2", "pid": 1, "children": [] }, { "id": 3, "name": "3", "pid": 1, "children": [ { "id": 4, "name": "4", "pid": 3, "children": [] } ] } ] } ] function treeToArray(tree) { let res = [] for (const item of tree) { const { children, ...i } = item if (children && children.length) { res = res.concat(treeToArray(children)) } res.push(i) } return res } treeToArray(tree)