已知原有数据 :
var data=[
{ id: 40, parentId: 31, note: "的萨达是" },
{ id: 20, parentId: 11, note: "的萨达是" },
{ id: 22, parentId: 20, note: "dsadas" },
{ id: 12, parentId: null, note: "dsadasad萨达s" },
{ id: 11, parentId: undefined, note: "dqwds" },
{ id: 24, parentId: 22, note: "搜索" },
{ id: 34, parentId: 22, note: "搜索" }
]
需要考虑的问题 :
不更改源数据
避免循环引用, 即 a的parentId为b, b的parentId为a
发挥你的大脑, 来个最优解
4 回答
PIPIONE
TA贡献1829条经验 获得超9个赞
const toTree =
(arr, pID) =>
arr
.filter(({ parentId }) => parentId == pID)
.map(a => ({
...a,
childers: toTree(arr.filter(({ parentId }) => parentId != pID), a.id)
}))
添加回答
举报
0/150
提交
取消