javascript - Convert table data to tree data JSON format (parent, child) d3.js dynamically?
问题描述
I want to visualize table data as tree data in d3.js
My input table data is
But i want tree data as:
[{"name":"SU1", "children":[{ "name":"DU1", "children":[{"name":"ST1"},{"name":"ST2"}]}, {"name":"DU2", "children":[]}]}, {"name":"SU2","children":[{ "name":"DU3", "children":[{"name":"ST3"}]}, {"name":"SU3","children":[]}]}]
Here my logic is if data value is null there shouldn't be any children for that node.
I have a code here in stack overflow it self but not working for my logic where do I change the logic such that i wont get the children for null values.
Below is the link for the code what I have tried...
How to convert Data table to tree json format dynamically?
Thanks in advance...
解决方案
您可以使用forEach
withreduce
方法来循环数据并构建嵌套数据结构,您还可以在其中检查当前元素是否是树中的最后一个节点,或者该值是否为 null,然后不添加 children 属性。
const data = [
['SU1', 'DU1', 'ST1'],
['SU1', 'DU1', 'ST2'],
['SU1', 'DU2', null],
['SU2', 'DU3', 'ST3'],
['SU3', null, null]
];
const result = []
const tree = {result}
data.forEach(a => {
a.reduce((r, name, i, arr) => {
if (!r[name]) {
const obj = {name}
r[name] = {result: []}
if (arr[i + 1] && name != null) {
obj.children = r[name].result
}
r.result.push(obj)
}
return r[name]
}, tree)
})
console.log(result)
推荐阅读
- sql-server - 如何使用 SQL Server 中其他表中的列值插入 xml 顶级属性节点
- python - 使用python将txt文件中的数据排序到列中
- php - 更改前缀后 Composer psr-4 autoload class not found 错误
- javascript - 是否可以在使用 NestJs 中的 ServeStaticModule 服务之前修改 index.html?
- fragment-shader - 片段着色器无法正确处理纹理
- java - 问题 - @ComponentScan(basePackageClasses = AdminController.class) <- 为什么它破坏了我的应用程序?
- azure - 用于 QnAmaker 输出订阅密钥的 ARM 模板
- javascript - 通过另一个变量将数组添加在一起
- javascript - React JS 和 TypeError
- kubernetes - Kubernetes如何划分persistentVolumeClaim的体积