[ { "id": "1666720833385607168", "createBy": null, "createId": null, "createDate": "2023-06-08 16:16:27", "updateBy": null, "updateId": null, "updateDate": null, "deleteFlag": null, "parentId": "0", "sourcePid": "1666720833385607168", "updateTime": null, "sourceAddress": "地址", "sourceCode": "CK0001", "sourceName": "资产分类树一级", "sourceStatus": 1, "sourceType": null, "notes": "备注", "children": [ { "id": "1666720833385607167", "createBy": null, "createId": null, "createDate": "2023-06-08 16:16:27", "updateBy": null, "updateId": null, "updateDate": null, "deleteFlag": null, "parentId": "1666720833385607168", "sourcePid": "1666720833385607168", "updateTime": null, "sourceAddress": "地址", "sourceCode": "CK0001", "sourceName": "资产分类树二级", "sourceStatus": 1, "sourceType": null, "notes": "备注", "children": null } ] }, { "id": "123456", "createBy": null, "createId": null, "createDate": "2023-06-08 09:50:32", "updateBy": null, "updateId": null, "updateDate": null, "deleteFlag": null, "parentId": "0", "sourcePid": "123456", "updateTime": null, "sourceAddress": "", "sourceCode": "LB0001", "sourceName": "测试类别", "sourceStatus": 1, "sourceType": null, "notes": "备注", "children": null } ]处理成lable,value的格式
时间: 2023-07-12 21:52:40 浏览: 164
可以使用 JavaScript 的 `Array.prototype.map` 方法,结合递归遍历树结构,将树节点转换为 `label` 和 `value` 属性的对象数组。代码示例如下:
```javascript
function processTreeToOptions(tree) {
return tree.map(node => {
const option = { label: node.sourceName, value: node.id };
if (node.children && node.children.length > 0) {
option.children = processTreeToOptions(node.children);
}
return option;
});
}
```
在这个示例中,`processTreeToOptions` 函数接受一个树结构数组作为参数,使用 `Array.prototype.map` 方法对每个节点进行处理。对于每个节点,我们创建一个包含 `label` 和 `value` 属性的对象,并检查当前节点是否有子节点。如果有,则递归调用 `processTreeToOptions` 函数,将子节点转换为 `children` 属性的数组,并将该数组添加到当前节点的对象中。
最后,`processTreeToOptions` 函数返回一个包含所有节点转换后的对象数组。这个数组可以直接传递给一些 UI 库中的组件,如 Ant Design 的 `Select` 组件。
示例数据处理后的结果如下:
```javascript
[
{
label: "资产分类树一级",
value: "1666720833385607168",
children: [
{
label: "资产分类树二级",
value: "1666720833385607167"
}
]
},
{
label: "测试类别",
value: "123456"
}
]
```
阅读全文