let x = [ { id: 'A', title: '第一层A', children: [ { id: 'A-1', title: '第二层A-1', children: [] } ] }, { id: 'B', title: '第一层B', children: null }, { id: 'C', title: '第一层C', children: [ { id: 'C-1', title: '第二层C-1', children: [] }, { id: 'C-2', title: '第二层C-2', children: [ { id: 'C-2-1', title: '第三层C-2-1', } ] }, { id: 'C-3', title: '第二层C-3', children: null }, { id: 'C-4', title: '第二层C-4', children: [ { id: 'C-4-1', title: '第三层C-4-1', } ] }, ] } ] var list =[] var recursiveFunction = function(){ var str = [] const getStr = function(list){ list.forEach(row=>{ if(row.children && row.children.length){ getStr(row.children) }else { str.push(row) } }) } getStr(x) list = str console.log(list) } recursiveFunction()
var list1 =[] var recursiveFunction1 = function(){ var str1 = [] const getStr1 = function(list1){ list1.forEach(row1=>{ if(!row1.children){ str1.push(row1) }else { getStr1(row1.children)
}
})
}
getStr1(x)
list1 = str1
// console.log(list1)
} recursiveFunction1()
var list2 =[] var ids="C-2-1" var recursiveFunction2 = function(data, id){ let res = []; const findIds = (data, temp = []) => { data.forEach((node,index)=>{ if(node.children==null){ node.children=[] } if (node.children.length > 0) { findIds(node.children, temp.concat(index)); } else { if (node.id == id) { temp.push(index) res = temp; } } }) } findIds(data, []); // console.log(res) return res; } recursiveFunction2(x,ids)