首页 > 解决方案 > 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

enter image description here

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...

标签: javascriptd3.js

解决方案


您可以使用forEachwithreduce方法来循环数据并构建嵌套数据结构,您还可以在其中检查当前元素是否是树中的最后一个节点,或者该值是否为 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)


推荐阅读