13

ネストされた JSON 構造の配列があり、深さが異なり、どこでも同じキーのセットではありません。

[
    {
        "name":"bob",
        "salary":10000,
        "friends":[
            {
                "name": "sarah",
                "salary":10000
            },
            {
                "name": "bill",
                "salary":5000
            }
        ]
    },
    {
        "name":"marge",
        "salary":10000,
        "friends":[
            {
                "name": "rhonda",
                "salary":10000
            },
            {
                "name": "mike",
                "salary":5000,
                "hobbies":[
                    {
                        "name":"surfing",
                        "frequency":10
                    },
                    {
                        "name":"surfing",
                        "frequency":15
                    }
                ]
            }
        ]
    },
    {
        "name":"joe",
        "salary":10000,
        "friends":[
            {
                "name": "harry",
                "salary":10000
            },
            {
                "name": "sally",
                "salary":5000
            }
        ]
    }
]

D3 を使用して、これをネストされた html テーブルとしてレンダリングしたかったのです。たとえば、友人の列には、行で参照されている個人の友人の名前と給与を示すテーブルがあります。これらのテーブルの 1 つに別のレベルのサブテーブルがある場合があります。

これを行う方法は、テーブルを再帰的に作成することだと思います。このような JSON 構造を取り、テーブル内にテーブルをレンダリングする Python プログラムを作成しましたが、これを行う最も簡単な方法は再帰的でした。d3.jsのドキュメントには、.each()呼び出すことができるものがあることがわかります。これは私が必要としているものだと確信しています。ウィキごと)。

D3でこれを行う良い方法はありますか? データの 2 次元マトリックスをテーブルとしてレンダリングするためのこの素晴らしい例を見つけました CSV ファイルにリンクされたテーブルの作成。そのチュートリアルでは、このデータ構造の最も外側のレベルをテーブルとしてレンダリングすることができましたが、必要に応じて再帰的にレベルに移動する方法に行き詰まっています。現在、それらはテーブルに「オブジェクト」として表示されるだけです通常の文字列や数値とは異なる扱いをしていないからです。

また、私の質問に似たこの他の質問/回答を見つけましたが、再帰がどこでどのように発生しているかを確認し、ニーズに合わせてソリューションを再適応するのに十分なほどJavaScriptを理解していません: How do I process data that is D3で複数のレベルをネストしましたか? . D3 の JSON データ構造のようなネストされたツリーを再帰的または反復的に処理するためのチュートリアルへのアドバイスやポインタは大歓迎です!

4

1 に答える 1

19

再帰関数はおそらく良いアプローチでしょう。考えられる実装の1つについては、以下のコードを参照してください(データがに格納されていると仮定しますjdata)。説明についてはコード内のコメントを参照し、ライブバージョンについてはこの要点を参照してください:http://bl.ocks.org/4085017

d3.select("body").selectAll("table")
    .data([jdata])
  .enter().append("table")
    .call(recurse);

function recurse(sel) {
  // sel is a d3.selection of one or more empty tables
  sel.each(function(d) {
    // d is an array of objects
    var colnames,
        tds,
        table = d3.select(this);

    // obtain column names by gathering unique key names in all 1st level objects
    // following method emulates a set by using the keys of a d3.map()
    colnames = d                                                     // array of objects
        .reduce(function(p,c) { return p.concat(d3.keys(c)); }, [])  // array with all keynames
        .reduce(function(p,c) { return (p.set(c,0), p); }, d3.map()) // map with unique keynames as keys
        .keys();                                                     // array with unique keynames (arb. order)

    // colnames array is in arbitrary order
    // sort colnames here if required

    // create header row using standard 1D data join and enter()
    table.append("thead").append("tr").selectAll("th")
        .data(colnames)
      .enter().append("th")
        .text(function(d) { return d; });

    // create the table cells by using nested 2D data join and enter()
    // see also http://bost.ocks.org/mike/nest/
    tds = table.append("tbody").selectAll("tr")
        .data(d)                            // each row gets one object
      .enter().append("tr").selectAll("td")
        .data(function(d) {                 // each cell gets one value
          return colnames.map(function(k) { // for each colname (i.e. key) find the corresponding value
            return d[k] || "";              // use empty string if key doesn't exist for that object
          });
        })
      .enter().append("td");

    // cell contents depends on the data bound to the cell
    // fill with text if data is not an Array  
    tds.filter(function(d) { return !(d instanceof Array); })
        .text(function(d) { return d; });
    // fill with a new table if data is an Array
    tds.filter(function(d) { return (d instanceof Array); })
        .append("table")
        .call(recurse);
  });    
}
于 2012-11-16T07:16:41.013 に答える