算法合集

福尔摩斯对我笑 2019-07-05 17431 次 3307条

树形结构反向解析

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

发表评论



 


已有 3307 条评论 1


  1. Evacycle 回复 2020年2月26日
  2. Evacycle 回复 2020年2月26日
  3. modern building construction

    Whats up this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding skills so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

    回复 2020年2月25日
  4. galvanized tc bolts

    Have you ever considered about including a little bit more than just your articles? I mean, what you say is valuable and all. Nevertheless just imagine if you added some great visuals or video clips to give your posts more, “pop”! Your content is excellent but with images and clips, this blog could undeniably be one of the most beneficial in its niche. Great blog!

    回复 2020年2月25日
  5. modern era construction

    Greetings! I know this is kind of off topic but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having problems finding one? Thanks a lot!

    回复 2020年2月25日
  6. Glory

    jungle scout alternative

    This is very attention-grabbing, You’re a very skilled blogger.
    I have joined your feed and look ahead to in search of extra of
    your magnificent post. Also, I have shared your
    website in my social networks

    回复 2020年2月25日
  7. tension control bolts

    Please let me know if you’re looking for a article writer for your site. You have some really good articles and I believe I would be a good asset. If you ever want to take some of the load off, I’d love to write some material for your blog in exchange for a link back to mine. Please blast me an email if interested. Regards!

    回复 2020年2月25日
  8. house cleaning

    Hey would you mind letting me know which hosting company you’re using? I’ve loaded your blog in 3 different internet browsers and I must say this blog loads a lot quicker then most. Can you suggest a good web hosting provider at a honest price? Thanks a lot, I appreciate it!

    回复 2020年2月25日
  9. superb maids discount code

    It’s a pity you don’t have a donate button! I’d most certainly donate to this fantastic blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this blog with my Facebook group. Talk soon!

    回复 2020年2月25日
  10. is tunnelbear a vpn

    jungle scout alternative

    You could definitely see your skills within the article you write.
    The sector hopes for more passionate writers such as you who aren’t afraid to mention how they believe.

    Always follow your heart.

    回复 2020年2月25日
  11. superb maids discount code

    My partner and I stumbled over here coming from a different web address and thought I should check things out. I like what I see so now i’m following you. Look forward to going over your web page repeatedly.

    回复 2020年2月25日
  12. maids

    Sweet blog! I found it while surfing around on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Many thanks

    回复 2020年2月25日
  13. Evacycle 回复 2020年2月24日
  14. mistyfq60

    Daily updated super sexy photo galleries
    http://ietnameseporn.jsutandy.com/?ally

    hot blooded porn our video home porn braces fetish girl porn free mobile phone porn pictures protect yourself from bad porn sites

    回复 2020年2月24日
  15. superb maids llc

    I absolutely love your blog and find nearly all of your post’s to be just what I’m looking for. Do you offer guest writers to write content for yourself? I wouldn’t mind publishing a post or elaborating on most of the subjects you write with regards to here. Again, awesome blog!

    回复 2020年2月24日
  16. http://neuphixsolutionscbd.net/

    I and also my friends were actually reading through the excellent
    points on your web blog and the sudden came up with a horrible feeling I never thanked the website
    owner for those secrets. Those young boys were definitely as a consequence passionate to see them and have
    now certainly been having fun with these things.
    I appreciate you for genuinely indeed kind and then for selecting such beneficial
    resources most people are really desirous to understand about.
    My personal honest regret for not saying thanks to sooner.

    回复 2020年2月24日
  17. home cleaning

    I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to create my own blog and would like to know where u got this from. thank you

    回复 2020年2月24日
  18. Pokerdewi

    Awesome blog! Is your theme custom made or did you download it from somewhere?
    A theme like yours with a few simple tweeks would really make my blog shine.
    Please let me know where you got your design. Kudos

    回复 2020年2月24日
  19. Evacycle 回复 2020年2月22日
  20. mobilCiz

    На самом деле, замена экрана хонор 10 i цена в сервисном центре – оптимальный выход для тех, кто явно не способен купить себе новенькую электронику и желает восстановить работоспособность свою.

    回复 2020年2月22日
  21. WayneViamy

    YOUTH Youth Celluvation http://tkfl777.com это Молодая кожа в любом возрасте без пластики и филлеров. Forever young skin without plastic surgery and fillers Available Now viber/whatsapp+12487304178

    回复 2020年2月22日
  22. Evacycle 回复 2020年2月22日
  23. Donald Mansi

    I found your this post while searching for information about blog-related research … It’s a good post .. keep posting and updating information. advice |

    回复 2020年2月21日
  24. Ricki Horwich

    This writing article support review is basically standard. This review is extremely useful to students accumulated some essay writing details for good essay. Such a essay writing articles are extremely impressive in order to viewers. Thank you pertaining to sharing your notions. anchor |

    回复 2020年2月21日
  25. https://www.jarumjam.com/

    Hi, i think that i saw you visited my web site thus i came to “return the favor”.I’m trying to find things to enhance my
    web site!I suppose its ok to use a few of your ideas!!

    回复 2020年2月21日
  26. bape hoodie

    I intended to post you that little remark to help say thanks the moment again considering the wonderful opinions you’ve provided in this case. It was quite pretty open-handed with people like you to deliver freely all a few people could have distributed for an e book in making some profit for their own end, most notably since you could possibly have tried it if you ever wanted. These tricks additionally served as a great way to comprehend other individuals have a similar zeal just like my personal own to find out much more related to this condition. I know there are millions of more pleasurable opportunities ahead for individuals that read carefully your website.

    回复 2020年2月20日
  27. Jule Sheth

    This website is indeed great with all its content and information. Also for beginners who are new in the filed of online gaming if they want Brave Frontier Hack they can visit our siye agree with |

    回复 2020年2月20日
  28. Lupe Nicolozakes

    Thanks for the best blog.it was very useful for me.keep sharing such ideas in the future as well. address |

    回复 2020年2月19日
  29. flying with a medical condition

    Hey there would you mind sharing which blog platform you’re using? I’m planning to start my own blog soon but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something unique. P.S Apologies for getting off-topic but I had to ask!

    回复 2020年2月19日
  30. best travel insurers for medical conditions

    Hi there! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my apple iphone. I’m trying to find a template or plugin that might be able to correct this problem. If you have any suggestions, please share. Appreciate it!

    回复 2020年2月19日
  31. Nicolasemese

    привет! я Хотело бы порекомендовать наш сайт – перейти Отличный сайт для проведения времени. Заходите и смотрите. Переходим к нам на сайт сюда. Сайт для вас

    回复 2020年2月19日
  32. performance marketing agency

    Appreciating the time and energy you put into your blog and detailed information you provide. It’s great to come across a blog every once in a while that isn’t the same old rehashed material. Fantastic read! I’ve bookmarked your site and I’m including your RSS feeds to my Google account.

    回复 2020年2月19日
  33. best travel blogs 2018

    Thanks on your marvelous posting! I quite enjoyed reading it, you happen to be a great author.I will be sure to bookmark your blog and may come back very soon. I want to encourage you to ultimately continue your great posts, have a nice evening!

    回复 2020年2月19日
  34. family day canada

    Have you ever thought about publishing an ebook or guest authoring on other sites? I have a blog centered on the same subjects you discuss and would really like to have you share some stories/information. I know my subscribers would enjoy your work. If you are even remotely interested, feel free to send me an e-mail.

    回复 2020年2月19日
  35. world travel family

    Heya! I know this is sort of off-topic but I needed to ask. Does building a well-established blog like yours take a massive amount work? I’m completely new to running a blog however I do write in my diary everyday. I’d like to start a blog so I will be able to share my experience and views online. Please let me know if you have any kind of recommendations or tips for brand new aspiring bloggers. Appreciate it!

    回复 2020年2月19日
  36. visitors guide

    Have you ever thought about including a little bit more than just your articles? I mean, what you say is fundamental and all. But think of if you added some great visuals or video clips to give your posts more, “pop”! Your content is excellent but with pics and video clips, this website could certainly be one of the most beneficial in its niche. Good blog!

    回复 2020年2月19日
  37. best cruise insurance

    Hello there! I know this is kinda off topic however I’d figured I’d ask. Would you be interested in exchanging links or maybe guest writing a blog article or vice-versa? My site discusses a lot of the same subjects as yours and I feel we could greatly benefit from each other. If you’re interested feel free to shoot me an e-mail. I look forward to hearing from you! Awesome blog by the way!

    回复 2020年2月19日
  38. WayneViamy

    Реклама в Pinterest самая эффективная https://youtu.be/pKbaZSBLSGE по продажам для интернет магазинов, ebay, etsy, amazon

    回复 2020年2月19日