Js traverses a tree array with closures

  • 2020-03-30 02:25:45
  • OfStack

When doing a company project, it is required to write a method whose parameters are a menu array collection and a menu id. The format of the menu array is treelike json, as shown below:

[{"id":28,"text":" Your company information ","children":[
     {"id":1,"text":" The 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":" The administrative information "},
                         {"id":27,"text":" High-level instruction "}]},
          {"id":22,"text":" Contact us "},
          {"id":26,"text":" Product display ","children":[
                         {"id":32,"text":" Power products "},
                         {"id":33,"text":" Accessories is introduced "}}]
 }] }]

Now given menu ids is 32, asked to find the corresponding item, and return the corresponding menu name, method is to loop through the array first, when the id of the item is equal to the specified id, remove the name of the menu, if is not equal to see if the current item to have children, if the children is not null and number greater than 0, the traverse children, would then use javascript closures, will traverse the children method in an anonymous way, so has been in the anonymous methods recursive itself, when faced with the same name id, jump out of the loop, Then return the menu name from the main method. The code is 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;
    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;
          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;

Related articles: