当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How can d3.js list the columns in a specified order?

问题描述:

I have a javascript object data:

[

{ 'sex': 'male', 'risk': '0.04', 'age_group': 'old' },

{ 'sex': 'female', 'risk': '0.03', 'age_group': 'young' },

{ 'sex': 'male', 'risk': '0.12', 'age_group': 'old' },

{ 'sex': 'female', 'risk': '0.04', 'age_group': 'old' },

]

And I also have an array which is used to specify the order of columns called metadata:

['sex', 'age_group', 'risk']

When using d3.js to visualize the data(currently I am using a table), I need to put them in the right order according to metadata.

Below is the code I am using to generate the table, without ordering the columns.

 var table = d3.select("#visualization_table");

table.append("thead");

table.append("tbody");

var thead = d3.select("thead")

.selectAll("th")

.data(metadata)

.enter()

.append("th")

.text(function(d) { return d });

var tr = d3.select("tbody").selectAll("tr")

.data(data)

.enter()

.append("tr");

var td = tr.selectAll("td")

.data(function(d) {return d3.values(d)})

.enter()

.append("td")

.text(function(d) {return d});

But the order will be like, 'sex', 'risk', 'age_group', while what I want is 'sex', 'age_group', 'risk'. Could anyone help?

网友答案:

You can do this by explicitly constructing the object in the nested .data() call, using metadata:

.data(function(d) {
  return metadata.map(function(m) { return d[m]; });
})

Complete demo here.

分享给朋友:
您可能感兴趣的文章:
随机阅读: