算法合集

福尔摩斯对我笑 2019-07-05 412 次 21条

树形结构反向解析

现有json结构如下:

  var objs = {
      id: 1,
      name: "第一个分组",
      pid: 0,
      label: "第一个分组",
      children: [
        {
          id: 3,
          name: "第一个分组的子分组",
          pid: 1
        },
        {
          id: 4,
          name: "第一个分组的第二个子分组",
          pid: 1,
          children: [
            {
              id: 5,
              name: "第一个分组的第二个子分组的第一个子分组",
              pid: 4,

              children: [
                {
                  id: 6,
                  name: "第一个分组的第二个子分组的第一个子分组的第一个分组",
                  pid: 4
                }
              ]
            }
          ]
        }
      ]
    };
    

需要的格式


[    {
        "id":3,
        "name":"第一个分组的子分组"
    },    {
        "id":4,
        "name":"第一个分组的第二个子分组"
    },    {
        "id":5,
        "name":"第一个分组的第二个子分组的第一个子分组"
    },    {
        "id":6,
        "name":"第一个分组的第二个子分组的第一个子分组的第一个分组"
    },    {
        "id":1,
        "name":"第一个分组"
    }]
    

算法

function toTreeData(objs) {
  var temp = [];
  var forFn = function(arr) {
      for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        temp.push({
          id: item.id,
          name: item.name
        });

        //如果有子元素进入递归
        if (item.children) {
          forFn(item.children);
        }
      }
    };


  if (objs.children) {
    forFn(objs.children);
  }

  temp.push({
    id: objs.id,
    name: objs.name
  });

  return temp;
}


var treeData = toTreeData(objs);
console.log(treeData);   //结束

根据最后一个找到整个家族


familyTree(arr, pid) {
var temp = [];
var forFn = function(arr, pid) {
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (item.id == pid) {
temp.push(item);
forFn(arr, item.pid);
}
}
};
forFn(arr, pid);
return temp;
}


找到某一父节点下的所有子节点

 sonsTree(arr, id) {
      var temp = [],
        lev = 0;
      var forFn = function(arr, id, lev) {
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i];
          if (item.pid == id) {
            item.lev = lev;
            temp.push(item);
            forFn(arr, item.id, lev + 1);
          }
        }
      };
      forFn(arr, id, lev);
      return temp;
    }

将数据写成树结构

toTree(data) {
      // 删除 所有 children,以防止多次调用
      data.forEach(function(item) {
        delete item.children;
      });
 
      // 将数据存储为 以 id 为 KEY 的 map 索引数据列
      var map = {};
      data.forEach(function(item) {
        map[item.id] = item;
      });
      //        console.log(map);
 
      var val = [];
      data.forEach(function(item) {
        // 以当前遍历项,的pid,去map对象中找到索引的id
        var parent = map[item.pid];
 
        // 如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
          val.push(item);
        }
      });
      return val;
    },

标签: 无

非特殊说明,本博所有文章均为博主原创。

头像也是LOGO
未来博客 博主大人
到了这个年纪,不应该再彷徨!

发表评论



 


已有 21 条评论 1


  1. curry 6

    A lot of thanks for your own hard work on this website. Betty really loves participating in investigations and it is easy to understand why. A lot of people know all concerning the dynamic manner you create priceless information via your web blog and even cause response from others on that topic and our favorite princess is in fact studying a lot. Take pleasure in the remaining portion of the year. Your doing a terrific job.

    回复 2019年10月24日
  2. nike air max shoes

    I as well as my pals have been checking out the nice suggestions found on your web blog then before long developed an awful suspicion I had not thanked the site owner for those secrets. All the guys are already certainly warmed to see all of them and have absolutely been loving them. Thanks for indeed being indeed considerate and then for choosing certain notable subject areas millions of individuals are really desperate to learn about. Our own sincere regret for not expressing gratitude to you earlier.

    回复 2019年10月23日
  3. nike shoes

    I’m just commenting to make you be aware of of the really good encounter my cousin’s princess developed using the blog. She discovered some issues, which include how it is like to possess an awesome helping mindset to get the rest without hassle fully grasp a number of tricky subject matter. You truly did more than readers’ expectations. Many thanks for giving these beneficial, trustworthy, educational and in addition cool guidance on that topic to Lizeth.

    回复 2019年10月23日
  4. golden goose shoes

    I simply wanted to make a quick note to be able to say thanks to you for some of the lovely tips and hints you are sharing on this website. My extended internet lookup has at the end of the day been honored with good quality facts and strategies to go over with my friends and classmates. I ‘d assert that most of us readers are quite fortunate to exist in a fabulous place with so many awesome individuals with very beneficial concepts. I feel really happy to have used your web page and look forward to many more amazing times reading here. Thanks a lot again for everything.

    回复 2019年10月21日
  5. https://letmejerk.com

    Excellent blog here!Also youг website loads ᥙp very fast!

    Ԝһat host arre you uѕing? Ϲan I get yоur affiliate llink to
    yoᥙr host? I wish mʏ website loaded up аѕ faѕt
    aѕ yours lol

    回复 2019年10月20日
  6. yeezy shoes

    I would like to point out my appreciation for your generosity in support of folks that need help on that concern. Your very own dedication to getting the solution all over ended up being surprisingly invaluable and have constantly enabled associates just like me to arrive at their endeavors. Your new informative useful information can mean much to me and further more to my office colleagues. With thanks; from all of us.

    回复 2019年10月20日
  7. curry 6 shoes

    Thanks for all of your efforts on this web page. My daughter enjoys managing internet research and it is obvious why. Most of us learn all about the powerful way you convey helpful steps via your blog and as well inspire response from other individuals on this theme so our favorite simple princess is without a doubt becoming educated a lot. Have fun with the rest of the new year. You are carrying out a remarkable job.

    回复 2019年10月18日
  8. nike epic react flyknit

    I simply wanted to send a simple note to be able to thank you for those unique instructions you are showing on this site. My rather long internet search has at the end of the day been rewarded with good quality knowledge to write about with my family and friends. I ‘d tell you that most of us website visitors are very endowed to dwell in a magnificent site with so many awesome professionals with valuable tactics. I feel truly blessed to have encountered the website and look forward to so many more thrilling times reading here. Thank you again for all the details.

    回复 2019年10月16日
  9. Helenunsette

    Hello.

    Where I can download XEvil for free on your website?
    Got information from your Support. XEvil is really the best program for captcha solving, but I need latest version of it.

    Thanks.

    回复 2019年10月16日
  10. curry 6

    I enjoy you because of your whole labor on this site. Debby really loves doing research and it’s obvious why. Most people know all regarding the compelling manner you convey invaluable techniques on this blog and as well as improve response from other people on this concern so our girl is without question being taught a lot. Have fun with the remaining portion of the new year. You’re the one doing a really good job.

    回复 2019年10月16日
  11. louboutin shoes

    I have to express appreciation to the writer just for rescuing me from this type of problem. Just after surfing around throughout the the web and seeing basics which are not powerful, I figured my entire life was well over. Existing without the presence of answers to the issues you’ve resolved by way of your main write-up is a crucial case, as well as the ones that might have negatively affected my career if I hadn’t come across your web site. Your main mastery and kindness in playing with the whole lot was tremendous. I’m not sure what I would have done if I had not discovered such a thing like this. It’s possible to at this time look forward to my future. Thank you so much for the reliable and amazing help. I will not be reluctant to suggest your blog post to any person who requires tips about this issue.

    回复 2019年10月15日
  12. cheap nba jerseys

    My wife and i ended up being so happy Edward managed to round up his research through your precious recommendations he made through the web site. It is now and again perplexing to just continually be handing out hints which often the others may have been selling. And now we discover we’ve got the website owner to give thanks to because of that. The main illustrations you’ve made, the simple web site navigation, the friendships you can give support to create – it’s got mostly astounding, and it is assisting our son in addition to us imagine that this topic is enjoyable, which is certainly exceptionally essential. Many thanks for everything!

    回复 2019年10月14日
  13. christian louboutin shoes

    I am also writing to make you know what a magnificent encounter my cousin’s child enjoyed studying the blog. She learned many things, not to mention how it is like to have a marvelous coaching heart to get many people just fully understand some complicated things. You actually exceeded my expectations. I appreciate you for offering such effective, dependable, explanatory and in addition fun tips about that topic to Evelyn.

    回复 2019年10月13日
  14. balenciaga

    I intended to draft you that little note to be able to thank you so much yet again for your remarkable suggestions you have documented in this case. It’s simply incredibly open-handed of you to convey openly what exactly some people could possibly have made available for an ebook in making some bucks on their own, mostly seeing that you might well have done it if you ever considered necessary. These tactics also acted as a fantastic way to know that other people have the identical desire really like my own to know a whole lot more on the subject of this matter. Certainly there are lots of more enjoyable sessions ahead for many who read your website.

    回复 2019年10月11日
  15. jordan shoes

    I am also writing to make you understand what a wonderful discovery our daughter had visiting yuor web blog. She realized lots of details, which include what it’s like to possess an excellent coaching heart to get most people without problems learn several very confusing subject matter. You truly exceeded my desires. Many thanks for showing those practical, trusted, edifying and in addition unique tips about this topic to Ethel.

    回复 2019年10月10日
  16. balenciaga sneakers

    My wife and i were now thankful when Jordan managed to round up his investigations through the precious recommendations he made out of the blog. It’s not at all simplistic to just possibly be releasing information and facts that the rest might have been selling. And we also keep in mind we have the website owner to give thanks to for this. The type of explanations you made, the simple website navigation, the relationships you make it possible to instill – it is everything sensational, and it is assisting our son and our family feel that the matter is exciting, which is certainly really pressing. Many thanks for everything!

    回复 2019年10月9日
  17. balenciaga speed

    My husband and i got absolutely delighted when Chris managed to carry out his investigations out of the ideas he acquired from your own web site. It is now and again perplexing to just always be giving away strategies that men and women may have been trying to sell. And we figure out we need the blog owner to be grateful to for that. These illustrations you’ve made, the easy web site navigation, the friendships you make it possible to promote – it is everything excellent, and it’s assisting our son and us consider that that idea is thrilling, and that is quite vital. Many thanks for the whole lot!

    回复 2019年10月8日
  18. yeezy shoes

    I happen to be commenting to make you be aware of what a wonderful encounter my cousin’s child undergone visiting your web site. She discovered several pieces, which include what it is like to have a very effective coaching spirit to make many more quite simply know precisely certain impossible issues. You really did more than people’s desires. I appreciate you for coming up with those necessary, trusted, revealing and in addition easy tips about your topic to Janet.

    回复 2019年10月8日
  19. 凌云

    老大,这个模板能分享吗?

    回复 2019年7月10日
    • 福尔摩斯对我笑

      怎么分享

      回复 2019年7月10日
  20. 天命

    fdsafdafsdafd

    回复 2019年7月10日