Get the level of a hierarchy

前端 未结 4 1939
心在旅途
心在旅途 2020-12-29 15:37

I have an array of objects, Where each object has an id and a ParentId property (so they can be arranged in trees). They are in no particular order

4条回答
  •  被撕碎了的回忆
    2020-12-29 16:18

    One way to address this without the need for recursion is to create a DOM hierarchy. For each item in the array, create a div and attach it to its parent. then walk the DOM and assign the levels (top is level 1, then add 1 for each child).

    I have set up a rough demo here: http://jsfiddle.net/4AqgM/

    An excerpt from the code:

    top.dataset.level="1";
    var topChildren=top.getElementsByTagName("div");
    for (var i=0;i

提交回复
热议问题