桑基图 plotly.js 来自需要的对象转换

sankey chart with plotly.js from an object conversion needed

所以我有一个对象需要转换成在 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": []
             }
           ]
         }
       ]
     }
   ]
 }
]

问题是我不知道对象数组的深度所以它必须自动生成。遍历对象数组并填充桑基图数据集的最佳方法是什么?

我通过创建两种递归方法找到了答案,一种用于标签,一种用于值。值数据集仍需改进,但图表现在显示正确。

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]);
     }
   }

}