最简练的代码将扁平化一维对象数组(具有id、pId或id、parentId或ID、PID)转换为结构化的数组,通过PID或parentId转换为有逻辑关系的树形结构数组(List转换为tree)

方法一 

flat2StructureArray(arr) {
    return arr.filter((father) => {
        let children = arr.filter((child) => father.ID == child.PID);
        children.length > 0 &&(father.children = children);
        return father.PID == '';
    })
} 

方法二

flatArray2TreeArrayByPID(arr) {
    const r = [], map = {};
    arr.forEach(v => map[v.ID] = v);
    arr.forEach(v => {
        const p = map[v.PID || v.pid || v.parentId];
        (p ? p.children || (p.children = []) : r).push(v);
    })
    return r;
},

逆向操作 

将有逻辑关系的树形结构数组转换为扁平化的一维对象数组(包含PID、ID父子关系)-CSDN博客文章浏览阅读99次。【代码】最简练的代码将扁平化的数组(具有id、pId或id、parentId或ID、PID)转换为结构化的数组,将扁平化的一位对象数组通过PID或parentId转换为有逻辑关系的树形结构数组。_id 和parentid 如何转换数据。最简练的代码将扁平化一维对象数组(具有id、pId或id、parentId或ID、PID)转换为结构化的数组,通过PID或parentId转换为有逻辑关系的树形结构数组(List转换为tree)_id 和parentid 如何转换数据-CSDN博客。https://blog.csdn.net/qq_37860634/article/details/136001605

java也有类似的工具hutool来完成扁平化数组→结构化数据的转换(List转换为tree)

使用hutool工具实现将普通集合数据转为树结构数据_hutool list转tree-CSDN博客文章浏览阅读986次。快速构建树查询_hutool list转treehttps://blog.csdn.net/weixin_51091628/article/details/129496830

你可能感兴趣的:(JavaScript)