需要对象转换的plotly.js的sankey图表

时间:2018-05-27 09:26:17

标签: angular recursion plotly sankey-diagram

所以我有一个对象需要转换为sankey diagram中可查看的内容。对象看起来像这样:

"DecisionTreeRegressionModel": [
{
  "  If (feature 28 <= 16.0)": [
    {
       "   If (feature 0 in {0.0})": [
         {
            "    Predict: 13.0": []
         }
       ]
    },
    {
      "   Else (feature 0 not in {0.0})": [
        {
          "    Predict: 16.0": []
        }
      ]
    }
  ]
},
{
  "  Else (feature 28 > 16.0)": [
    {
       "   If (feature 28 <= 40.0)": [
         {
           "    Predict: 40.0": []
         }
       ]
     },
     {
       "   Else (feature 28 > 40.0)": [
         {
           "    If (feature 0 in {0.0})": [
             {
                "     Predict: 45.0": []
             }
           ]
         },
         {
           "    Else (feature 0 not in {0.0})": [
             {
               "     Predict: 50.0": []
             }
           ]
         }
       ]
     }
   ]
 }
]

问题是我不知道对象数组的深度,因此必须自动生成它。循环遍历对象数组并填充sankey图表数据集的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

我通过创建2个递归方法找到答案,一个用于标签,一个用于值。值数据集仍然需要工作,但图表现在正确显示。

build_labels(node : Node){
   let key : String = node.name;
   let already_added : boolean = false;
   if(this.labels_array.indexOf(key) > -1){
     already_added = true;
   }
   if(!already_added){
     this.labels_array.push(key);
   }

   if(node.children!=null && node.children.length>0){
     for(let i : number = 0 ; i < node.children.length ; i++){
       this.build_labels(node.children[i]);
     }
   }

}


build_chart(node : Node){

   let key : String = node.name;
   let father_index : number = this.labels_array.indexOf(key);

   if(node.children!=null && node.children.length>0){
     for(let i : number = 0 ; i < node.children.length ; i++){
       let child_key : String = node.children[i].name;
       let child_index : number = this.labels_array.indexOf(child_key);
       this.source_array.push(father_index);
       this.target_array.push(child_index);
       this.value_array.push(1);
       this.build_chart(node.children[i]);
     }
   }

}