【问题标题】:Recursively (or iteratively) make a nested html table with d3.js?递归地(或迭代地)用 d3.js 创建一个嵌套的 html 表?
【发布时间】:2012-10-31 12:05:58
【问题描述】:

我有一组嵌套的 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 表。例如,朋友列将有表格显示行中引用的个人的朋友的姓名和薪水。有时其中一个表会有另一个级别的子表。

我想这样做的方法是递归地创建表。我编写了一个 python 程序,它采用这样的 JSON 结构,并在表中呈现表,最简单的方法是递归。我在 d3.js 文档中看到有一个可以调用的 .each() 东西,我确信这是我需要的,我只需要一点点提升就可以到达那里 (https://github.com/mbostock/d3/wiki/Selections#wiki-each)。

那么在 D3 中有没有很好的方法来做到这一点?我发现了这个很好的例子,用于将二维数据矩阵渲染为表格Creating a table linked to a csv file。通过该教程,我能够将这个数据结构的最外层呈现为一个表格,但我被困在如何根据需要递归地进入各个级别,截至目前它们在表格中显示为“对象”因为我没有将它们与普通字符串和数字区别对待。

我还发现了与我的问题类似的另一个问题/答案,但我真的不太了解 javascript,无法了解递归发生的位置/方式,并重新调整解决方案以满足我的需求:How do I process data that is nested multiple levels in D3?。任何关于递归或迭代处理嵌套树(如 D3 中的 JSON 数据结构)的教程的建议或指针将不胜感激!

【问题讨论】:

    标签: javascript html d3.js


    【解决方案1】:

    递归函数可能是个好方法。请参阅下面的代码了解一种可能的实现方式(假设您的数据存储在jdata 中)。请参阅代码中的 cmets 以获得一些解释,并查看此 Gist 以获得实时版本: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);
      });    
    }
    

    【讨论】:

    • 它在 javascript 文件中包含非法字符!
    • @msqar - 不,您只需要指定它是 UTF-8:请参阅 github.com/mbostock/d3/wiki/Upgrading-to-3.0。您需要一个文档类型,一个 标记,并且您的脚本需要像这样包含:
    • 很好,您可以将嵌套对象显示为单行表吗?我自己尝试过这样做,但不知道应该在哪里将对象转换为单项数组。
    猜你喜欢
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    相关资源
    最近更新 更多