我能够使用D3.js创建并将数据加载到Select元素(Dropdown)中。我遇到的主要问题是在下拉列表中我看到所有名称(重复)。我想只看到不同的名字。这是一个工作示例:http://jsfiddle.net/khnumtemu/43oaczq8/
var dataset = [
{
"SalesRepName":"KIM MIKE (110)",
"FieldSalesManagerName":"MILLER BRIAN"
},
{
"SalesRepName":"JAISWAL LOKESH (111)",
"FieldSalesManagerName":"MILLER BRIAN"
},
{
"SalesRepName":"QUINTERN GEOFFREY (112)",
"FieldSalesManagerName":"MILLER BRIAN"
},
{
"SalesRepName":"OKOYE MAXIMUS (114)",
"FieldSalesManagerName":"MILLER BRIAN"
},
{
"SalesRepName":"STARGHILL TREVOR (115)",
"FieldSalesManagerName":"OPEN POSITION"
},
{
"SalesRepName":"JARDOT BENJAMIN (318)",
"FieldSalesManagerName":"MILLER BRIAN"
},
{
"SalesRepName":"MICCICHE TERRY (319)",
"FieldSalesManagerName":"MILLER BRIAN",
},
{
"SalesRepName":"KAMENOVA TEODORA (401)",
"FieldSalesManagerName":"OPEN POSITION"
},
{
"SalesRepName":"SHERIDAN BRIAN (402)",
"FieldSalesManagerName":"OPEN POSITION"
},
{
"SalesRepName":"KNEIP CHARLES (403)",
"FieldSalesManagerName":"OPEN POSITION"
}
]
d3.select("body").append("select")
.classed('colorSelect',true)
.selectAll("option")
.data(dataset)
.enter()
.append("option")
.attr("value",function(d){ return d.FieldSalesManagerName;})
.text(function(d){ return d.FieldSalesManagerName;})
.sort(function(a, b) {return d3.ascending(a.FieldSalesManagerName, b.FieldSalesManagerName);});
// Data OnLoad
d3.select("body").selectAll("p")
.data(dataset)
.enter()
.append("p")
// Data Updated on Selected Change
d3.select("select")
.on("change", function(d){
var sel = d3.select(".colorSelect").node().value;
d3.select("body").selectAll("p")
.data(dataset)
.text(function(d){
if(d.FieldSalesManagerName === sel){
return d.SalesRepName;
}
})
});
答案 0 :(得分:2)
由于存在大量数据重复,您的代码正在为更好的数据结构而死。由于您使用的是d3
,我首先会将其强制转换为map。
var map = d3.map();
dataset.forEach(function(d){
if (!map.has(d.FieldSalesManagerName)){
map.set(d.FieldSalesManagerName, [d.SalesRepName])
} else {
map.get(d.FieldSalesManagerName).push(d.SalesRepName);
}
});
你的下拉然后变成:
d3.select("body").append("select")
.classed('colorSelect',true)
.selectAll("option")
.data(map.keys())
.enter()
.append("option")
.attr("value",function(d){ return d;})
.text(function(d){ return d; });
然后您的on
更改可以避免循环和比较:
d3.select("select")
.on("change", function(d){
var sel = d3.select(".colorSelect").node().value;
d3.select("body").selectAll("p")
.data(map.get(sel))
.text(function(d){
return d;
})
});
更新了fiddle。