function flattenTree(tree) {
let flatData = [];
function flatten(node) {
flatData.push(node);
if (node.children) {
node.children.forEach(child => flatten(child));
}
}
flatten(tree);
return flatData;
}
// 示例树结构的数据
const treeData = {
id: 1,
name: "Root",
children: [
{
id: 2,
name: "Child 1",
children: [
{
id: 3,
name: "Grandchild 1",
children: []
},
{
id: 4,
name: "Grandchild 2",
children: []
}
]
},
{
id: 5,
name: "Child 2",
children: []
}
]
};
// 调用扁平化函数
const flattenedData = flattenTree(treeData);
console.log(flattenedData);
js实现扁平化树结构数据
最新推荐文章于 2024-01-23 16:03:06 发布