算法合集

福尔摩斯对我笑 2019-07-05 11916 次 2609条

树形结构反向解析

现有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;
    },

根据ID找到最近的父级

  function findIndexArray(data, id, indexArray) {
        let arr = Array.from(indexArray);
        for (let i = 0, len = data.length; i < len; i++) {
          if (data[i].children) {
            arr = []; 
            arr.push(data[i].pid);
          }
          if (data[i].id === id) {
            return arr;
          }
          let children = data[i].children;
          if (children && children.length) {
            let result = findIndexArray(children, id, arr);
            if (result) return result;
          }
        }
        return false;
      }


 console.log(findIndexArray(data, 3, [])); 

标签: 无

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

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

发表评论



 


已有 2609 条评论 1


  1. jordan shoes

    Thanks so much for giving everyone an extremely pleasant opportunity to read critical reviews from this web site. It’s usually so terrific and also full of a lot of fun for me and my office fellow workers to visit your website no less than three times in one week to read the latest stuff you have. And indeed, I’m also always impressed with all the fabulous hints you give. Selected two ideas in this post are indeed the most efficient we have all ever had.

    回复 2020年1月22日
  2. Bokep

    bookmarked!!, I like your website!

    回复 2020年1月22日
  3. aplikasi vivoslot

    Good post. I learn something totally new and challenging on sites I stumbleupon on a daily basis. It will always be useful to read articles from other writers and use a little something from their web sites.

    回复 2020年1月22日
  4. karisini escort sitesinde satan pic

    karisini escort sitesinde satan pic

    回复 2020年1月22日
  5. Nonton Bokep

    Great post! We are linking to this great post on our website. Keep up the great writing.

    回复 2020年1月22日
  6. situs togel terpercaya

    It’s hard to come by experienced people in this particular subject, but you seem like you know what you’re talking about! Thanks

    回复 2020年1月22日
  7. aplikasi vivoslot

    Excellent blog post. I definitely love this site. Keep writing!

    回复 2020年1月22日
  8. judi togel

    Hi, I do think this is a great website. I stumbledupon it 😉 I am going to revisit once again since I book-marked it. Money and freedom is the best way to change, may you be rich and continue to help others.

    回复 2020年1月22日
  9. Nonton Bokep

    Wonderful article! We are linking to this particularly great content on our site. Keep up the great writing.

    回复 2020年1月22日
  10. judi togel

    Excellent article! We will be linking to this particularly great post on our website. Keep up the good writing.

    回复 2020年1月22日
  11. house wood door models

    Good web site! I really love how it is easy on my eyes and the data are well written. I’m wondering how I might be notified when a new post has been made. I’ve subscribed to your RSS which must do the trick! Have a nice day!

    回复 2020年1月22日
  12. karisini escort sitesinde satan pic

    karisini escort sitesinde satan pic

    回复 2020年1月22日
  13. CalvinSib

    herbal relief https://alijuguetes.es/lorazepam-en-farmacia-pfz.php drug urine screening

    回复 2020年1月21日
  14. howtogetbetterinlife.com

    Hi! I just would like to give you a big thumbs up for the great info you have got right here on this post. I am coming back to your blog for more soon.

    回复 2020年1月21日
  15. judi togel

    Your style is really unique compared to other people I’ve read stuff from. Thank you for posting when you’ve got the opportunity, Guess I’ll just bookmark this web site.

    回复 2020年1月21日
  16. bandar togel terpercaya

    Way cool! Some very valid points! I appreciate you writing this post plus the rest of the site is extremely good.

    回复 2020年1月21日
  17. mainbadarq

    I blog often and I genuinely appreciate your information. Your article has really peaked my interest. I’m going to take a note of your website and keep checking for new information about once a week. I subscribed to your Feed too.

    回复 2020年1月21日
  18. Hoa Qua Sach Anh Xanh

    It¡¦s really a nice and useful piece of info. I am happy that you shared this useful info with us. Please keep us up to date like this. Thank you for sharing.

    回复 2020年1月21日
  19. bandar togel terpercaya

    Wonderful post! We are linking to this great content on our website. Keep up the great writing.

    回复 2020年1月21日
  20. Perusahaan Rekrutmen

    Next time I read a blog, I hope that it won’t fail me just as much as this one. After all, I know it was my choice to read through, but I actually thought you would have something interesting to talk about. All I hear is a bunch of moaning about something you can fix if you weren’t too busy seeking attention.

    回复 2020年1月21日
  21. Janecycle 回复 2020年1月21日
  22. www.merpati99.info

    Hello there, I believe your blog might be having browser compatibility problems. When I look at your site in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping issues. I simply wanted to give you a quick heads up! Aside from that, great website!

    回复 2020年1月21日
  23. check out this one from Primaxtesto

    If you are going for finest contents like me, only pay a visit this
    web page every day because it presents quality contents, thanks

    回复 2020年1月21日
  24. situs togel

    Greetings! Very useful advice within this article! It’s the little changes that produce the biggest changes. Many thanks for sharing!

    回复 2020年1月21日
  25. judi togel

    Wonderful article! We are linking to this great content on our website. Keep up the great writing.

    回复 2020年1月21日
  26. bandar togel terpercaya

    This website definitely has all the information and facts I wanted concerning this subject and didn’t know who to ask.

    回复 2020年1月21日
  27. www.familyhealthavenue.net

    Great site you’ve got here.. It’s hard to find quality writing like yours these days. I truly appreciate people like you! Take care!!

    回复 2020年1月21日
  28. Jasa Website Murah

    Aw, this was an extremely nice post. Taking the time and actual effort to generate a really good article… but what can I say… I put things off a whole lot and don’t seem to get anything done.

    回复 2020年1月21日
  29. situs togel terpercaya

    This site was… how do I say it? Relevant!! Finally I’ve found something that helped me. Appreciate it!

    回复 2020年1月21日
  30. bandar togel terpercaya

    Hello! I could have sworn I’ve been to your blog before but after going through a few of the posts I realized it’s new to me. Anyways, I’m certainly happy I found it and I’ll be book-marking it and checking back frequently!

    回复 2020年1月21日
  31. togel online

    Good day! I just would like to give you a huge thumbs up for the great information you’ve got right here on this post. I will be coming back to your web site for more soon.

    回复 2020年1月21日
  32. Ad Incubator

    Good day very cool site!! Man .. Beautiful ..
    Wonderful .. I will bookmark your web site and take the feeds additionally?I’m glad to
    search out numerous helpful information here within the publish, we want develop extra strategies on this regard,
    thanks for sharing.

    回复 2020年1月21日
  33. download aplikasi vivoslot

    You made some really good points there. I checked on the internet for additional information about the issue and found most people will go along with your views on this site.

    回复 2020年1月21日
  34. idnpoker.com

    Spot on with this write-up, I truly believe this website needs a great deal more attention. I’ll probably be back again to see more, thanks for the info!

    回复 2020年1月21日
  35. https://unpastiche.org/

    Pretty! This was an extremely wonderful article. Many thanks for providing this information.

    回复 2020年1月21日
  36. daftar vivoslot

    Spot on with this write-up, I seriously believe that this web site needs a lot more attention. I’ll probably be back again to see more, thanks for the information!

    回复 2020年1月21日
  37. https://laotracarboneria.net/

    Hi! I could have sworn I’ve been to this web site before but after looking at many of the posts I realized it’s new to me. Anyways, I’m definitely pleased I discovered it and I’ll be book-marking it and checking back often!

    回复 2020年1月21日
  38. ERA4D

    Right here is the right web site for anybody who wants to find out about this topic. You realize a whole lot its almost tough to argue with you (not that I personally will need to…HaHa). You definitely put a new spin on a topic that’s been written about for ages. Excellent stuff, just excellent!

    回复 2020年1月21日
  39. idnplay

    The next time I read a blog, Hopefully it doesn’t fail me just as much as this particular one. I mean, I know it was my choice to read through, nonetheless I really believed you’d have something helpful to say. All I hear is a bunch of complaining about something that you could fix if you weren’t too busy searching for attention.

    回复 2020年1月21日
  40. TommyRem

    FluzAthletic also create fantastic custom items, with a quick and helpful service and value for money.
    Or followed your dog down to the river And ran into an ole baptizin.
    You d better run, better run, outrun my gun.
    http://gardanakalenfefyn.info/mp3/no-4-velocissimo-andr-tchaikowsky-maciej-grzybowski-vienna-symphony-orchestra-paul-daniel.php Pitbull got involved in the game himself when he started appearing on Miami mixtapes.
    With the purchase of Kobo VIP Membership, you re getting 10 off and 2x Kobo Super Points on eligible items.
    Mas nГЈo vou mais hesitar, nГЈo mais, nГЈo mais Isso nГЈo pode esperar, eu sou seu.

    回复 2020年1月21日
  41. agen vivo slot

    Hello there, There’s no doubt that your blog might be having internet browser compatibility problems. Whenever I look at your web site in Safari, it looks fine however, if opening in IE, it has some overlapping issues. I simply wanted to provide you with a quick heads up! Apart from that, wonderful blog!

    回复 2020年1月21日
  42. https://hajenol.de/

    I’m more than happy to find this website. I want to to thank you for your time for this particularly fantastic read!! I definitely loved every little bit of it and i also have you saved as a favorite to look at new information in your website.

    回复 2020年1月21日
  43. pkvgamesonline

    I used to be able to find good advice from your content.

    回复 2020年1月21日
  44. Kimcycle 回复 2020年1月21日
  45. link alternatif vivoslot

    Hi! I just would like to give you a big thumbs up for the excellent info you have right here on this post. I will be returning to your site for more soon.

    回复 2020年1月21日
  46. vivoslot login

    Right here is the perfect site for anyone who wants to understand this topic. You understand so much its almost tough to argue with you (not that I actually will need to…HaHa). You definitely put a fresh spin on a subject that has been written about for a long time. Excellent stuff, just wonderful!

    回复 2020年1月21日
  47. aplikasi vivoslot

    I was excited to uncover this site. I want to to thank you for your time for this particularly fantastic read!! I definitely enjoyed every part of it and i also have you book-marked to see new things in your site.

    回复 2020年1月21日
  48. judi online

    Right here is the right webpage for anyone who would like to find out about this topic. You realize a whole lot its almost hard to argue with you (not that I personally would want to…HaHa). You definitely put a new spin on a topic that’s been discussed for many years. Excellent stuff, just wonderful!

    回复 2020年1月21日
  49. vivoslot mobile

    Spot on with this write-up, I truly believe this website needs much more attention. I’ll probably be returning to see more, thanks for the advice!

    回复 2020年1月21日
  50. video bokep

    Hi, I do believe this is an excellent web site. I stumbledupon it 😉 I am going to come back once again since i have bookmarked it. Money and freedom is the greatest way to change, may you be rich and continue to guide others.

    回复 2020年1月21日