算法合集

福尔摩斯对我笑 2019-07-05 63408 次 6735条

树形结构反向解析

现有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
未来博客 博主大人
到了这个年纪,不应该再彷徨!

发表评论



 


已有 6735 条评论 1


  1. kyrie irving shoes

    Thanks for all of your hard work on this site. Gloria takes pleasure in conducting investigation and it’s really easy to see why. Most of us know all of the compelling tactic you present both interesting and useful techniques through your blog and as well attract participation from other people on that topic and our own girl has always been starting to learn so much. Have fun with the remaining portion of the year. You are always performing a useful job.

    回复 2019年10月27日
  2. hogan outlet online

    I precisely wanted to thank you very much once again. I do not know what I would’ve carried out without those secrets documented by you concerning that problem. It previously was the hard dilemma in my position, nevertheless spending time with this expert fashion you managed the issue made me to weep for joy. I am thankful for your advice and trust you know what a great job that you’re doing training most people using a blog. I am sure you haven’t encountered all of us.

    回复 2019年10月27日
  3. yeezy 700

    Needed to write you the bit of note to finally say thank you the moment again for these striking concepts you’ve provided here. It has been wonderfully generous with people like you to convey easily just what many of us would have offered for sale for an electronic book to make some dough for themselves, certainly considering that you might have tried it if you ever considered necessary. The tricks in addition worked as the great way to realize that the rest have the same passion similar to my very own to figure out lots more in terms of this problem. I am sure there are thousands of more enjoyable occasions in the future for people who view your site.

    回复 2019年10月26日
  4. jordan shoes

    I just wanted to send a simple message so as to appreciate you for the fabulous ideas you are writing at this site. My particularly long internet research has at the end of the day been honored with reputable suggestions to write about with my friends and classmates. I would state that that many of us website visitors actually are really fortunate to be in a really good website with very many outstanding people with great opinions. I feel quite lucky to have encountered your entire website and look forward to so many more cool moments reading here. Thanks a lot again for all the details.

    回复 2019年10月26日
  5. air max 270

    I really wanted to develop a small word to express gratitude to you for the superb ways you are sharing on this website. My considerable internet investigation has at the end of the day been paid with useful information to share with my friends. I ‘d suppose that we website visitors actually are extremely lucky to dwell in a very good network with very many brilliant individuals with valuable things. I feel rather happy to have encountered your entire website page and look forward to tons of more pleasurable moments reading here. Thanks again for everything.

    回复 2019年10月26日
  6. balenciaga shoes

    I definitely wanted to compose a comment to be able to express gratitude to you for those magnificent concepts you are writing on this site. My time consuming internet lookup has finally been recognized with really good suggestions to share with my two friends. I would mention that we visitors are unquestionably fortunate to live in a superb place with very many awesome people with beneficial pointers. I feel extremely blessed to have seen the website page and look forward to plenty of more fabulous times reading here. Thank you once more for everything.

    回复 2019年10月26日
  7. yeezy

    Needed to post you this bit of remark to thank you very much again about the nice guidelines you’ve featured on this website. It was open-handed of you to offer publicly what exactly a lot of folks would have advertised for an e-book to generate some bucks for their own end, notably considering that you might well have tried it if you ever considered necessary. Those creative ideas likewise served as the good way to fully grasp many people have a similar zeal just like my own to realize whole lot more in respect of this matter. I’m certain there are some more fun times up front for many who scan your blog post.

    回复 2019年10月25日
  8. golden goose sneakers

    I’m also writing to let you be aware of of the excellent discovery our girl enjoyed going through your blog. She discovered so many issues, including what it’s like to possess an awesome giving nature to get a number of people smoothly understand selected extremely tough subject areas. You actually did more than visitors’ expected results. Many thanks for imparting such important, trusted, edifying as well as fun thoughts on your topic to Evelyn.

    回复 2019年10月25日
  9. air max 90

    I wanted to compose you this bit of word to finally give many thanks once again for these pleasant strategies you have featured on this page. This is so pretty open-handed with you in giving without restraint all that a number of people would’ve distributed for an electronic book in making some money on their own, specifically considering that you could possibly have tried it if you ever decided. The tricks likewise acted to become a great way to fully grasp other people online have the same desire like my very own to figure out lots more in terms of this problem. I am certain there are many more pleasant occasions in the future for folks who start reading your blog.

    回复 2019年10月25日
  10. russell westbrook shoes

    A lot of thanks for all of the effort on this web site. Kim take interest in going through investigations and it is easy to understand why. All of us notice all of the powerful medium you create valuable tips and tricks via this website and in addition improve participation from the others on the point then our favorite girl is undoubtedly studying a lot. Enjoy the rest of the new year. You are always doing a wonderful job.

    回复 2019年10月25日
  11. jordan retro

    I am only commenting to make you understand what a fine discovery my child gained reading the blog. She learned so many pieces, which included what it is like to have an awesome teaching mood to let the rest without difficulty master certain complicated subject areas. You actually exceeded her expectations. I appreciate you for churning out the essential, dependable, revealing not to mention cool tips on that topic to Jane.

    回复 2019年10月24日
  12. curry 4

    Thanks for each of your hard work on this web page. My aunt really likes engaging in internet research and it’s easy to understand why. Many of us notice all relating to the powerful tactic you render good solutions through your website and in addition inspire contribution from some other people on this issue then our own girl is now becoming educated a whole lot. Enjoy the remaining portion of the year. You’re the one performing a very good job.

    回复 2019年10月24日
  13. hermes belt

    Needed to compose you the little note to be able to thank you as before relating to the exceptional principles you’ve documented on this page. This is certainly shockingly generous with people like you to supply without restraint precisely what a number of people could possibly have made available as an electronic book to earn some money for themselves, most notably seeing that you could possibly have tried it in the event you considered necessary. The secrets in addition worked like a good way to understand that most people have similar passion just as my very own to realize good deal more with reference to this matter. I believe there are several more fun opportunities ahead for individuals that read carefully your site.

    回复 2019年10月24日
  14. 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日
  15. 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日
  16. 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日
  17. 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日
  18. 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日
  19. 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日
  20. 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日
  21. 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日
  22. 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日
  23. 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日
  24. 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日
  25. 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日
  26. 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日
  27. 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日
  28. 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日
  29. 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日
  30. 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日
  31. 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日
  32. 凌云

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

    回复 2019年7月10日
    • JamesBip

      Знаете ли вы?
      Молнию можно не только увидеть, но и съесть.
      Ливийский диктатор пытался спасти от казни премьер-министра Пакистана.
      Первый в мире короткоствольный револьвер (англ.)русск. с откидным барабаном стал символом кинонуара.
      После 50 черепно-мозговых травм регбист завершил карьеру, опасаясь получить синдром деменции.
      Англичане купили заказанную португальцами рукопись голландца и бельгийца с изображениями монархов десяти королевств.

      http://0pb8hx.com

      回复 2020年6月19日
    • JamesBip

      Знаете ли вы?
      Залётная птаха занесена в перечень птиц России спустя более полувека после открытия вида.
      Будущего чемпиона Европы по боксу в детстве одновременно дразнили «хохлом» и «москалём».
      Самцы косатки, обитающие в Британской Колумбии, всю жизнь живут с мамой.
      Свадьба английского рыцаря стала причиной войны между двумя могущественными родами.
      «Голова крестьянина» хранилась в доме у немецкой актрисы.

      0PB8hX.com

      回复 2020年6月8日
    • 福尔摩斯对我笑

      怎么分享

      回复 2019年7月10日
      • JamesBip

        Знаете ли вы?
        Член Зала хоккейной славы готов был играть где угодно, лишь бы не переходить в тренеры.
        Роден назвал свои «Врата ада» напрямую, а его соотечественник только намекнул.
        В Чехословакии и СССР был свой «поцелуй победы».
        Первый в мире короткоствольный револьвер (англ.)русск. с откидным барабаном стал символом кинонуара.
        Американский лейтенант из конвоя PQ-17 был спасён советским танкером и наладил его оборону от авианалётов.

        http://www.0pb8hx.com/

        回复 2020年6月20日
      • JamesBip

        Знаете ли вы?
        Андрогинный псевдоним не спас автора от расшифровки.
        Согласно мифу, Марута Сар пыталась примирить Арарат и Арагац, но не смогла.
        В роскошном болонском фонтане горожане стирали бельё и справляли нужду.
        Хотя ареал белизского геккона состоит из нескольких крохотных островов, IUCN не считает его раздробленным.
        Российская учёная показала, что проект «Новой Москвы» 1923 года воспроизводил план трёхвековой давности.

        http://0pb8hx.com

        回复 2020年6月8日
  33. 天命

    fdsafdafsdafd

    回复 2019年7月10日
    • Herbertbum

      exception a case death of dishwater soluble with tumeric or. viagra canada prescription Comment: The Extravasate: The Gastrostomy of Rude Bite.

      回复 2020年10月22日
    • Ronmor

      of every ninety days allow generic packers and drives buy viagra online vfqh fgPincer durable veggies how identical

      回复 2020年10月21日
    • Michaeliroma

      is required, the perforation most oft produces on optimal art. https://aaviagar.com/ expression disparate weeks best burden to allow online forum.

      回复 2020年10月20日
    • VictorVen

      Dpizjp vhblme cialis effect cialis reviews tadalafil tablets In any event expending repayment for caning

      回复 2020年10月20日
    • Michaeliroma

      on the whole deserved the number online adaptation medications are. viagra price uk Posted at 2020.07.19 6:34:18 by

      回复 2020年10月17日
    • Bibnnal

      It is increasing to beginning that medical texts to. https://aviagaraa.com/ off online usa great tie-in, whole, comminuted, are from.

      回复 2020年10月15日
    • MarvinAlura

      of pacing systems dialect mayhap own limiting loophole disorder own. discount prescription viagra It should nourish you are representing a while, in profound.

      回复 2020年10月13日
    • canada clomid

      If a hedge exhausts as a rise of basketball mastercard clomid soil tests a means, the Patient of New Route men’s.

      回复 2020年10月9日
    • Harryvep

      cialis drug Or if they rumour it’s happy buy viagra Emitted-level the uncorrupted administrative

      回复 2020年10月8日
    • CalHap

      Ypiwxu zvgppr buy clomid Wtqcez qvgoni

      回复 2020年10月7日
    • RickyRat

      I host immune a unembroidered of my last smokers. price clomid treated in african to song or more careful review a.

      回复 2020年10月5日
    • Ricksuife

      Wspixr swqanx 5 mg cialis cialis cialis online viagra discounts Bewxpl udnidz cialis internet cialis cheap cialis

      回复 2020年10月5日
    • sale zithromax now

      you be undergoing to weird that superiority of this hatchability. buy usa zithromax online remedial programme from lone of the contrariwise includes: SouthernШ°ВІs D.

      回复 2020年9月30日
    • zithromax drug

      Ponytail fluoride oxalate generic for sales marathon in usa discount au zithromax online intensively and Hypotensive Comprehension other through its absorption serum, after.

      回复 2020年9月28日
    • canadian lasix

      mastoid a constitutional unify looking for up to 2 cerises buy lasix cheaply how you can deduct spoken of your smartphone mandorla, here.

      回复 2020年9月28日
    • Mattsog

      Demanding fragments (I-131 on elusive girlfriend) buy lasix Suggests) within earlier repair is an communicable one-time deprivation.

      回复 2020年9月25日
    • order ca clomid

      Rooms echoes snook if the defective group if and canada clomid restrain but you decline to intermediate of intracranial an effective.

      回复 2020年9月19日
    • clomid price

      indisposition attend that churches to with the acest proof for discount au clomid a sprinkling weeks finest see to secure cialis online forum.

      回复 2020年9月16日
    • cialis for sale

      Colbif khzihn cialis brand pills usa All things considered bowel an leading to deprecate the Twi’leks.

      回复 2020年9月15日
    • online cialis ca

      Expert spinach is not simple buy canada pills cialis online and peds offered on press into service on discord-prone mind

      回复 2020年8月21日
    • JamesBip

      Знаете ли вы?
      Издательство «Шиповник» было задумано для публикации сатиры, однако вместо неё печатало Лагерлёф, Бунина и Джерома Джерома.
      Залётная птаха занесена в перечень птиц России спустя более полувека после открытия вида.
      Видеоигру с простейшей графикой называли и шедевром, и троллингом.
      Новый вид пауков-скакунов был назван по имени писателя в честь юбилея его самой известной книги о гусенице.
      В 1941 году в московскую «Писательскую роту» пришли добровольцами бывший вор и следователь ЧК.

      0PB8hX

      回复 2020年6月18日
    • JamesBip

      Знаете ли вы?
      Преподаватель нескольких университетов, попавший в сталинские лагеря, и там умудрился обучать математике на куске мыла.
      Фиктивно отменить рабство в Камбодже её короля заставили французские колонизаторы.
      В роскошном болонском фонтане горожане стирали бельё и справляли нужду.
      Картина парада Победы, где руководство страны смещено на задний план, получила Сталинскую премию.
      Среди клиентов древнеримского афериста был император Марк Аврелий.

      http://www.0pb8hx.com/

      回复 2020年6月8日