"result": [
{
"id": "051ef8f0-74d7-4127-b58a-3c733b501400",
"text": "demo",
"code": null,
"count": null,
"children": [
{
"id": "dd634612-56d1-4b94-b2b5-b16d590edb1d",
"text": "test",
"code": null,
"count": null,
"children": []
}
]
},
{
"id": "1ed3d9b5-da90-4469-8779-1c391c1bdc28",
"text": "企业演示用",
"code": null,
"count": null,
"children": [
{
"id": "2541a86f-2a84-4877-8a97-c6f5f704327b",
"text": "销售业务部",
"code": null,
"count": null,
"children": []
},
{
"id": "7628de3b-a103-445c-b197-26a696c67d66",
"text": "营销管理部",
"code": null,
"count": null,
"children": []
},
{
"id": "aa30600c-b5d9-4259-bf31-9443e1e9245d",
"text": "市场部",
"code": null,
"count": null,
"children": []
},
{
"id": "b863a930-74fe-45e8-890d-9f1221cd108c",
"text": "信息管理部",
"code": null,
"count": null,
"children": []
},
{
"id": "e59ce330-571e-476d-8b20-e1312764017e",
"text": "台规部",
"code": null,
"count": null,
"children": []
},
{
"id": "fbf3d423-b9b7-475a-97b4-27106c0d861e",
"text": "医学事务部",
"code": null,
"count": null,
"children": []
}
]
}
]
后台返回的树型结构
//扁平化数据
let flatten = (list) => {
let arr = []
for (let item of list) {
if (item.children && Object.keys(item.children).length > 0) {
arr = arr.concat(flatten(item.children))
} else {
arr.push(item)
}
}
return arr
}
deptOptions.value = flatten(res)
当解读这个 flatten 函数时,我们将分步骤地解释其功能和工作原理。flatten 函数的目标是将传入的树形结构数据扁平化为一个数组,使得所有节点都在同一级别上,方便后续处理和展示。
这里再次列出 flatten 函数的代码:
js
let flatten = (list) => {
let arr = [];
for (let item of list) {
if (item.children && item.children.length > 0) {
arr = arr.concat(flatten(item.children));
} else {
arr.push(item);
}
}
return arr;
};
deptOptions.value = flatten(res);
现在我们来逐步解释 flatten 函数的工作流程:
flatten函数接收一个树形结构数据列表list作为输入参数。- 在函数内部,定义了一个空数组
arr,用于存放扁平化后的结果。 - 进行
for...of循环遍历传入的list列表。for...of循环用于遍历数组中的每个元素,这里的item表示当前正在遍历的元素。 - 对于当前遍历的节点
item,检查它是否有子节点,即是否存在item.children。如果item.children存在且长度大于 0,说明item有子节点。 - 如果
item有子节点,则进行递归调用。这里递归调用的目的是将子节点继续扁平化。通过flatten(item.children),将item.children数组传递给flatten函数,获取扁平化后的结果,并将其与arr数组进行合并。 - 如果
item没有子节点,直接将item添加到arr数组中。 - 继续循环,处理下一个节点。
- 循环结束后,所有节点都已经被处理并扁平化,最终得到一个扁平化后的数组
arr。 - 返回扁平化后的数组
arr。