共计 742 个字符,预计需要花费 2 分钟才能阅读完成。
// 有父子级从属关系的对象数组
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}
})
}
正文完
发表至: javascript
2021-01-22