D3如何正确获取json对象的键值INSIDE

时间:2017-03-21 06:35:22

标签: javascript json d3.js

我正在尝试根据返回的json对象的键值生成我的列标题。但是它返回[0,1]而不是[key[1],key[2]]

这是我的json数据,我尝试使用D3获取此对象的关键字(这是"标签","计数" for示例)作为我的列标题而不是静态插入。

[
  {
  "Label": "External-Partner-Induced",
  "Count": 9
  },
{
 "Label": "Null",
 "Count": 1
},
{
 "Label": "FCTS-Induced",
 "Count": 66
},
{
 "Label": "EI-Partner-Induced",
 "Count": 78
 }
]

这是我的d3代码:

d3.json('dataQualityIssuesCategory.json', function (error,data) {

    function tabulate(data, columns) {
    var table = d3.select('body').append('table')
    var thead = table.append('thead')
    var tbody = table.append('tbody');

    // append the header row
    thead.append('tr')
      .selectAll('th')
      .data(columns).enter()
      .append('th')
        .text(function (column) { return column; });

    // create a row for each object in the data
    var rows = tbody.selectAll('tr')
      .data(data)
      .enter()
      .append('tr');


   // create a cell in each row for each column
    var cells = rows.selectAll('td')
      .data(function (row) {
        return columns.map(function (column) {
          return {column: column, value: row[column]};
        });
      })
      .enter()
      .append('td')
        .text(function (d) { return d.value; });
     return table;
     }

    // render the table
    tabulate(data, [d3.keys(data)[0], d3.keys(data)[1]]); // 2 column table
});

tabulate函数是我试图获取列标题的关键字段的地方,但上面的代码似乎是获取整个对象而不是值INSIDE。示例:[0,1]作为列标题而不是[Label, Count] example

1 个答案:

答案 0 :(得分:1)

请注意data是一个对象数组而不是对象。因此,要获取对象的键,您应该在数组中的一个对象上应用d3.keys函数。像这样 -

tabulate(data, d3.keys(data[0])); //data[0] is an object, applying d3.keys(data[0]) will return [Label, Count]



var data = [{
    "Label": "External-Partner-Induced",
    "Count": 9
  },
  {
    "Label": "Null",
    "Count": 1
  },
  {
    "Label": "FCTS-Induced",
    "Count": 66
  },
  {
    "Label": "EI-Partner-Induced",
    "Count": 78
  }
];

function tabulate(data, columns) {
  var table = d3.select('body').append('table')
  var thead = table.append('thead')
  var tbody = table.append('tbody');

  // append the header row
  thead.append('tr')
    .selectAll('th')
    .data(columns).enter()
    .append('th')
    .text(function(column) {
      return column;
    });

  // create a row for each object in the data
  var rows = tbody.selectAll('tr')
    .data(data)
    .enter()
    .append('tr');


  // create a cell in each row for each column
  var cells = rows.selectAll('td')
    .data(function(row) {
      return columns.map(function(column) {
        return {
          column: column,
          value: row[column]
        };
      });
    })
    .enter()
    .append('td')
    .text(function(d) {
      return d.value;
    });
  return table;
}
// render the table
tabulate(data, d3.keys(data[0]));

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;