一个完整的初学者的问题,我很害怕。来自几个对象数组,例如:
var ct1 = [
{name: "Africa", id: 1},
{name: "America", id: 2},
{name: "Asia", id: 3},
{name: "Europe", id: 4},
{name: "Oceania", id: 5}
];
var ct2 = [
{key: "Africa", l: "AF"},
{key: "Asia", l: "AS"},
{key: "Europe", l: "EU"}
];
var countries = [
{name: "Togo", ctt: "Africa"},
{name: "India", ctt: "Asia"},
{name: "Iran", ctt: "Asia"},
{name: "Peru", ctt: "America"}
];
我试图在两个上下文中检索我选择中的常用值:
var continent = d3.select("body").selectAll("div").data(c1)
// Here I would like to filter the data,
// in order to get only the number of divs whose keys match the names in c1
.append("div");
continent.append("p")
// Here, I would like to create paragraphs for each object in countries
// whose "ctt" is also present in "c1", retrieving the name value in the process.
预期结果如下:
<div id="AF">
<p>Togo</p>
</div>
<div id="AS"></div>
<p>India</p>
<p>Iran</p>
<div id="EU"></div>
我正在努力掌握地图并获得功能,但暂时失去了。非常感谢 - 也是为了您的放纵。
答案 0 :(得分:1)
查看有关绑定嵌套结构的本教程:https://bost.ocks.org/mike/nest/#data。在创建父div
之后,您可以在它们上面调用.data
来将数据绑定到它们的子节点,如下所示:
var ct1 = [{
name: "Africa",
id: 1
},
{
name: "America",
id: 2
},
{
name: "Asia",
id: 3
},
{
name: "Europe",
id: 4
},
{
name: "Oceania",
id: 5
}
];
var ct2 = [{
key: "Africa",
l: "AF"
},
{
key: "Asia",
l: "AS"
},
{
key: "Europe",
l: "EU"
}
];
var countries = [{
name: "Togo",
ctt: "Africa"
},
{
name: "India",
ctt: "Asia"
},
{
name: "Iran",
ctt: "Asia"
},
{
name: "Peru",
ctt: "America"
}
];
var continent = d3.select("body").selectAll("div").data(ct2);
continent.enter().append('div').attr('id', function(d) {
return d.l
});
var p = continent.selectAll('p').data(function(d) {
var cc = [];
countries.forEach(function(x) {
if (x.ctt == d.key) {
cc.push(x.name);
}
});
return cc;
});
p.enter().append('p').text(function(d) {
return d
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>