如何遍历d3嵌套数据

时间:2018-06-01 16:55:38

标签: d3.js

我在csv数据上使用d3.nest之后有一个嵌套数据数组,就像这个小提琴nested data一样。我想编写一个可重用的函数,递归循环遍历这种类型的数组,并为每个键创建组,并且仅在" key"找不到。对于每个级别的组,我想设置一个y域。

let nestedData = [{
        key: "A",
        values: [{
            key: "ab",
            values: [{
                key: "xy",
                values: [{
                  name: "tom"
                }]
              },
              {
                key: "tu",
                values: [{
                  name: "corin"
                }]
              }
            ]
          },
          {
            key: "cd",
            values: [{
              key: "xy",
              values: [{
                name: "nancy"
              }]
            }]
          }
        ]
      },
      {
        key: "B",
        values: [{
            key: "ab",
            values: [{
              key: "xy",
              values: [{
                name: "tom"
              }]
            }]
          },
          {
            key: "cd",
            values: [{
              key: "xy",
              values: [{
                name: "nancy"
              }]
            }]
          }
        ]
      }]

最终目标是绘制一个具有y轴分组的水平条形图(如此nested x axis image中的x轴分组

1 个答案:

答案 0 :(得分:0)

创建一个名为// Swift let dispatchGroup = DispatchGroup() let dispatchQueue = DispatchQueue.init(label: "AssetQueue") var uploadedAssets = [String]() let folderName: String = UUID().uuidString dispatchQueue.async { for i in 0..<photos.count { dispatchGroup.enter() let photo: UIImage = photos[i] let fileName: String = "\(folderName)/\(i)" let assetRef = Storage.storage().reference().child("photos/\(fileName)") let metaData = StorageMetaData() metaData.contentType = "image/jpg" if let dataToUpload = UIImageJPEGRepresentation(photo, 0.75) { assetRef.putData( dataToUpload, metaData: metaData, completion: { (_, error) in uploadedAssets.append("photos/\(fileName)") dispatchGroup.leave() } ) } } } dispatchGroup.notify(queue: dispatchQueue) { Alamofire.request( "https://<some_url>", method: .post, parameters: [ "uploadedAssets": uploadedAssets ] ) } 的类:

node

创建一个export class Node { public id: number; public attr: any[] = []; public children: Node[] = []; } 类:

recursion

警告

  1. 此代码编写为export class recursion { private nodes: any[] = []; public parse(ont: any): any { let linkedTree = this.parse_node(jsonInput); // console.log({'nodes': this.nodes}); return {'nodes': this.nodes} } private parse_node(jsonVal: any): any { let node = new Node(); node.id = this.nodes.length; this.nodes.push({ name: jsonVal.key, id: this.nodes.length, }); for (let value of jsonVal.values) { this.nodes.push({ name: value.name, id: this.nodes.length, }); node.attr.push(this.nodes.length); } for (let eachVal in jsonInput.values) { if (jsonInput.values.hasOwnProperty(eachVal)) { // recursion.. node.children.push( this.parse_node(jsonVal['values'][eachVal]) ); } } return node; }

  2. 我不是一个计算机科学家,递归不是我的强项,而是继续提出这个答案。也许你可以根据自己的需要调整逻辑。