需要将以下树形结构转成扁平化数组,同时添加一个从父级到子级的路径数组。
let tree = [
{
id: 1,
title: "grandfather",
children: [
{
id: 3,
title: "father"
},
{
id: 4,
title: "father2",
children: [{
id: 6,
title: "child1"
}]
}
]
},
{
id: 2,
name: "grandfather2",
children: [{
id: 5,
name: "father3"
}]
}
];
let list = [
{ id: 1, title: "grandfather", path: ['grandfather'] },
{ id: 3, title: "father", path: ['grandfather', 'father'] },
{ id: 4, title: "father2", path: ['grandfather', 'father2'] },
{ id: 6, title: "child1", path: ['grandfather', 'father2', 'child1'] },
{ id: 2, title: "grandfather", path: ['grandfather2'] },
{ id: 5, title: "father3", path: ['grandfather2', 'father3'] },
];
递归问题实在有点让我头疼,没有能解出来,因此请教一下万能的 V 友有没有什么好的解法。
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.