js中 树形数据 拍平 为数组 有parentid
的情况下,可以使用递归的方式遍历树形数据,并将每个节点的信息存储到一个数组中。
具体实现可以参考以下代码:
// 假设树形数据为以下格式
const treeData = [
{ id: 1, name: '节点1', parentid: null },
{ id: 2, name: '节点2', parentid: 1 },
{ id: 3, name: '节点3', parentid: 1 },
{ id: 4, name: '节点4', parentid: 2 },
{ id: 5, name: '节点5', parentid: 3 },
];
// 定义一个函数,用于将树形数据拍平为数组
function flattenTree(treeData, parentId = null) {
const result = [];
// 遍历树形数据
treeData.forEach(item => {
// 如果当前节点的父节点id等于指定的parentId(或者parentId为null且当前节点没有父节点),则将当前节点添加到结果数组中
if (item.parentid === parentId || (parentId === null && !item.parentid)) {
result.push(item);
// 递归调用函数,将当前节点的子节点也添加到结果数组中
result.push(...flattenTree(treeData, item.id));
}
});
return result;
}
// 调用函数将树形数据拍平为数组
const flattenedData = flattenTree(treeData);
console.log(flattenedData);
执行以上代码,输出结果为:
[
{ id: 1, name: '节点1', parentid: null },
{ id: 2, name: '节点2', parentid: 1 },
{ id: 4, name: '节点4', parentid: 2 },
{ id: 3, name: '节点3', parentid: 1 },
{ id: 5, name: '节点5', parentid: 3 }
]
可以看到,树形数据已经被成功拍平为了一个数组。
原文地址: https://www.cveoy.top/t/topic/51e 著作权归作者所有。请勿转载和采集!