Home >Web Front-end >JS Tutorial >js method to traverse tree array using closure_javascript skills
When doing a company project, you are required to write a method. The parameters of the method are a menu array collection and a menu id. The format of the menu array is tree json, as shown below:
{"id":1,"text":"Company Culture"},
{"id":2,"text":"Recruitment Plan"},
{"id":6,"text":"Company News","children":[
{"id":47,"text":"Industry News"}]},
{"id":11,"text":"Internal News","children":[
{"id":24,"text":"Administrative Information"},
{"id":27,"text":"High-level instructions"}]},
{"id":22,"text":"Contact us"},
{"id":26,"text":"Product Display","children":[
{"id":32,"text":"electrical products"},
{"id":33,"text":"Accessories Introduction"}}]
}] }]
The menu id given now is 32. It is required to find the corresponding item and return the corresponding menu name. The method is to loop through the array first. When the id of the item is equal to the specified id, take out the menu name. If it is not equal to Then see if the current item has children. If the children are not empty and the number is greater than 0, then traverse the children. At this time, you need to use the closure of javascript and put the method of traversing the children in an anonymous method, so that it is always in the anonymous method. The recursion itself, when encountering an id with the same name, jump out of the loop, and then return the obtained menu name from the main method. The code is as follows: