var data = { 0: {YY: "string0", HLS: "string0", YZ: "string0"}, 1: {DV: "string1", TYH: "string1", NM: "string1"}, 2: {NG: "string2", EFY: "string2", WRE: "string2"}, }; 将此数据修改为dtree 数据格式 带有本身id 和父节点id
时间: 2023-07-03 20:31:06 浏览: 79
数据格式转换
可以尝试以下代码将数据格式转换为 dtree 数据格式:
```
var data = {
0: {YY: "string0", HLS: "string0", YZ: "string0"},
1: {DV: "string1", TYH: "string1", NM: "string1"},
2: {NG: "string2", EFY: "string2", WRE: "string2"},
};
var dtreeData = [];
for (const [parentId, children] of Object.entries(data)) {
const parent = {id: parentId, title: parentId};
let childList = [];
for (const [childId, childValue] of Object.entries(children)) {
childList.push({id: childId, title: childValue});
}
parent.children = childList;
dtreeData.push(parent);
}
console.log(dtreeData);
```
结果如下:
```
[
{"id": "0", "title": "0", "children": [
{"id": "YY", "title": "string0"},
{"id": "HLS", "title": "string0"},
{"id": "YZ", "title": "string0"}
]},
{"id": "1", "title": "1", "children": [
{"id": "DV", "title": "string1"},
{"id": "TYH", "title": "string1"},
{"id": "NM", "title": "string1"}
]},
{"id": "2", "title": "2", "children": [
{"id": "NG", "title": "string2"},
{"id": "EFY", "title": "string2"},
{"id": "WRE", "title": "string2"}
]}
]
```
其中,每个对象代表一棵树的根节点,`id` 为节点的 ID,`title` 为节点的显示文本,`children` 为子节点列表。如果节点没有子节点,则 `children` 属性为空数组。
阅读全文