乐趣区

关于javascript:父子级数组排序

// 有父子级从属关系的对象数组
const list = [{ id: 1, name: "all"},
    {id: 2, name: "Z", pId: 1},
    {id: 4, name: "B", pId: 1},
    {id: 16, name: "Z-y", pId: 2},
    {id: 34, name: "Z-y-1", pId: 16},
    {id: 65, name: "B-x", pId: 4},
    {id: 98, name: "Z-b", pId: 2},
    {id: 127, name: "B-2", pId: 4}
] 
// 排序化为 (父子级挨着):[{ id: 1, name: "all"},
    {id: 2, name: "Z", pId: 1},
    {id: 16, name: "Z-y", pId: 2},
    {id: 34, name: "Z-y-1", pId: 16},
    {id: 98, name: "Z-x", pId: 2},
    {id: 4, name: "B", pId: 1},
    {id: 65, name: "B-1", pId: 4},
    {id: 127, name: "B-2", pId: 4}
] 

如果只有两层的嵌套, 就不须要递归了,比较简单:

let temp = list.map(i => ({ ...i, sortNum: parseFloat(`${i.pId}${!!i.pId ? '.' : ''}${i.id}`) }))
temp = _.sortBy(temp, 'sortNum')

能够嵌套多层的话,我采纳的是双递归,太菜了想不到更好的办法了,望指教!!!
// 先转树
https://segmentfault.com/a/11…

// 再

function tree2Arr(tree) {
    tree.forEach(i => {newArr.push(i);
        if (i.children) {tree2Arr(i.children)
        } else {return}
    })
}
退出移动版