A method to traverse a tree-like array with a closure in JS _javascript tips

Source: Internet
Author: User
Tags anonymous closure

When you do a company project, you need to write a method whose parameters are a menu array set and a menu ID, and the menu array is in the form of a tree json, as shown here:

Copy Code code as follows:
[{"id": "Text": "Company Information", "Children": [

{"id": 1, "text": "Company Culture"},

{"id": 2, "text": "Recruitment Plan"},

{"id": 6, "text": "Company News", "Children": [

{"id": $, "text": "Industry News"}]},

{"id": One, "text": "Internal News", "Children": [

{"id": "Text": "Administrative Information"},

{"id": "," "Text": "High-level Indicator"}]},

{"id": "Text": "Contact Us"},

{"id": "Text": "Product display", "Children": [

{"id": "Text": "Power Products"},

{"id":, "Text": "Accessories Introduction"}]

}] }]

The menu ID given now is 32, requires that the corresponding item be found, and the corresponding menu name is returned by looping through the array first, and when the ID of the item is equal to the specified ID, the menu name is taken out, if not equal to whether the current item has children, if the children is not empty and the quantity is greater than 0, Then iterate over the children, then use the JavaScript closure, the traversal of the children method in an anonymous method, so that the anonymous method has been recursive itself, when encountered the same name ID, jumped out of the loop, and then returned from the Main method of the menu name, the code is as follows:

Copy Code 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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.