Recursively find the corresponding node
Enter an ID as follows to find the structure corresponding to the ID
var arr =[
{id: 1.children: []},
{id: 2.children: []},
{id: 3.children: []},
{id: 4.children: []},
{id: 5.children: []},
{
id: 6.children: [{id: 7.children: [{id: 9.children] : []}}, {id: 8.children: []}]},]; The method is as follows:function digui(arr, id) {
for(let i = 0; i< arr.length; i++) {
if(arr[i].id === id){
return arr[i]
} else {
if(arr[i].children.length ! = =0) {return digui(arr[i].children, id)
}
}
}
}
console.log(digui(arr, 9)); //{id: 9, children:[]}
console.log(digui(arr, 6));
/ / the result:
/ / {
// id: 6,
// children: [
/ / {
// id: 7,
// children: [{id: 9, children:[]}]
/ /}, {
// id: 8,
// children: []
/ /}
/ /]
/ /}
Copy the code
Recursively find all child node names that do not have children
var data = [
{
name: "Everything".children: [{name: "Fruit".children: [{name: The word "apple".children: [{name: 'Green apple'.children: [{name: 'Northern Rice'}, {name: 'Southern rice'}]}, {name: 'Red Apple'}}]]}, {name: 'staples'.children: [{name: "Rice"}]}, {name: 'Articles of life'.children: [{name: "Computer".children: [{name: 'Lenovo Computer'}, {name: Apple Computer}]},
{name: "Utility class".children: [{name: "Hoe"}, {name: "The hammer"}]},
{name: "Articles of daily use".children: [{name: "Shampoo"}, {name: "Body wash."}]}]}]function didui(arr) {
let arrList = ' '
function f(arr) {
arr.forEach(item= > {
if(item.children) {
arguments.callee(item.children)
} else {
arrList += item.name + '; ';
}
})
}
f(arr)
return arrList;
}
console.log(didui(data)); // Northern rice; Southern rice; Red apple; Rice; Lenovo Computer; Apple Computer; Hoe. The hammer; The shampoo. Bath dew;
Copy the code