When working on a company project, you need to write a method, the parameters of the method are a menu array collection and a menu id, and the format of the menu array is a tree-like json, as shown below:
The code copy is as follows:[{"id":28,"text":"Company Information","children":[
{"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 indication"}]},
{"id":22,"text":"Contact Us"},
{"id":26,"text":"Product Display","children":[
{"id":32,"text":"electricity product"},
{"id":33,"text":"Accessories introduction"}}]
}] }]
The menu id given is now 32, and you need 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, look at the current Is there a child in the item? If the child is not empty and the number is greater than 0, then iterate through the child. At this time, you need to use the closure of JavaScript and place the method of traversing children in an anonymous method, so that you can recurse yourself in the anonymous method. , When an id with the same name is encountered, the loop will jump out, and then return the obtained menu name from the main method. The code is as follows:
Copy the code as follows: function getMenuName(menus, id) {
var name = "" ;
for (var i = 0; i < menus.length; i++) {
if (menus[i].id == id) {
name = menus[i].text;
break;
}
else {
(function () {
var m = arguments[0];
var menuid = arguments[1];
for (var j = 0; j < m.length; j++) {
if (m[j].id == menuid) {
name = m[j].text;
break;
}
else if m[j].children != null && m[j].children.length > 0) {
arguments.callee(m[j].children, val);//Recursive anonymous method
}
}
})(menus[i].children, id);
}
}
return name;
}