2017-07-05 5 views
0

D3のnewbです。私は親、子データを作成したいインデックスから親子ネストJSONを作成

[ 
    { 
    "health": "OK", 
    "name": "new A", 
    "index": "A", 
    "children": [ 
     { 
     "health": "SEVERE", 
     "name": "new AB", 
     "index": "A > B", 
     "children": [ 
      { 
      "health": "OK", 
      "name": "new ABC", 
      "index": "A > B > C" 
      } 
     ] 
     }, 
     { 
     "health": "SEVERE", 
     "name": "new AD", 
     "index": "A > D", 
     "children": [ 
      { 
      "health": "OK", 
      "name": "new ADE", 
      "index": "A > D > E" 
      } 
     ] 
     } 
    ] 
    } 
] 

[ 
    { 
    "health": "OK", 
    "name": "new A", 
    "index": "A" 
    }, 
    { 
    "health": "SEVERE", 
    "name": "new AB", 
    "index": "A > B" 
    }, 
    { 
    "health": "OK", 
    "name": "new ABC", 
    "index": "A > B > C" 
    }, 
    { 
    "health": "OK", 
    "name": "new ADE", 
    "index": "A > D > E" 
    }, 
    { 
    "health": "SEVERE", 
    "name": "new AD", 
    "index": "A > D" 
    } 
] 

私はJSON上から親子ネストされたデータを以下の作成したい:私はJSONの次の型を持っているd3.jdバージョン3 を使用していますインデックスを通じて。 したがって、インデックスが "A> B"で、 "A"が親で、 "B"が子である場合。

これは私が持っているサンプルデータです。大きなデータのだから、パフォーマンスを上げたい

d3またはjqueryでオブジェクトのネストされた親子JSONフォームの配列を作成することは可能ですか?

+0

'object'のネストされた親子JSON形式の配列を作成します - それは、より簡単かつ非多忙です –

答えて

0

私はそれをしました。私は親のIDを追加する必要があります。

var data = [ 
 
    { 
 
    "health": "OK", 
 
    "name": "new A", 
 
    "index": "A" 
 
    }, 
 
    { 
 
    "health": "SEVERE", 
 
    "name": "new AB", 
 
    "index": "A > B" 
 
    }, 
 
    { 
 
    "health": "OK", 
 
    "name": "new ABC", 
 
    "index": "A > B > C" 
 
    }, 
 
    { 
 
    "health": "OK", 
 
    "name": "new ADE", 
 
    "index": "A > D > E" 
 
    }, 
 
    { 
 
    "health": "SEVERE", 
 
    "name": "new AD", 
 
    "index": "A > D" 
 
    } 
 
] 
 

 
    function fnGetParentID(index) { 
 
        var indexArr = index.split(' > '); 
 
        var parentIndex = ''; 
 
        if(indexArr.length !== 1){ 
 
         parentIndex = index.replace(" > " + indexArr[indexArr.length - 1], '') 
 
        } 
 
        return parentIndex; 
 
       }; 
 

 
function fnCreateStrunture(f) { 
 
        return f.sort(function (a, b) { 
 
         return a.index.length < b.index.length ? 1 : a.index.length == b.index.length ? a.index < b.index ? -1 : 1 : -1; 
 
        }).reduce(function (p, c, i, a) { 
 
         c.ParentID = fnGetParentID(c.index); 
 
         var parent = !!c.ParentID && a.find(function (e) { 
 
           return e.index === c.ParentID; 
 
          }); 
 
         !!parent ? !!parent.children && parent.children.push(c) || (parent.children = [c]) : p.push(c); 
 
         return p; 
 
        }, []); 
 
       }; 
 
          
 
var nestedJson = fnCreateStrunture(data); 
 

 
document.getElementById("nested").innerHTML = JSON.stringify(nestedJson, undefined, 2);
<pre id="nested"></pre>

関連する問題