扁平结构数据变成嵌套结构数据(树状结构)

1.扁平结构

pid:当前对象的父级level等级

level:当前对象的level等级

 2.嵌套结构

 3.代码展示

3.1.定义扁平结构的数据array

pid:当前对象的父级level等级

level:当前对象的level等级

     

 3.2.js部分

        // 定义一个新数组
        var chapterTree = [];
flatArray.forEach(c
=> { // 给扁平数据数组的每一个内容项加上一个children属性,属性值为[] c.children = [];
if(c.pid == 0){ // 把没有父级的内容项添加到chapterTree新数组中,定义所有的初级父级 // 之后,往这些初级父级的children属性中添加内容项,见下面的else判断 chapterTree.push(c) }else{ // 通过当前遍历的每一个内容项的pid属性,在flatArray数组中,通过level属性寻找其父级 const theparent = flatArray.find( function(item){ return item.level === c.pid } ); // 把当前遍历的内容项,添加到父级的children属性中去 theparent.children.push(c); } })

3.3.打印出效果

    console.log(chapterTree);

           

       

原文地址:https://www.cnblogs.com/pwindy/p/15796965.html