在 D3.js 中,我尝试遍历 geojson 文件以查找特定属性的值。例如,我想遍历整个 geojson 文件,如果键 state
的值等于 KS
,则返回该数据。
我是 D3 的新手,我还没有找到任何可以让我这样做的东西。我的方法可能有缺陷,因此非常感谢任何建议。
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "KDDC",
"state": "KS",
"properties": {
"name": "Dodge City Regional Airport",
"address": "100 Airport Road, Dodge City, KS, United States"
},
"geometry": {
"type": "Point",
"coordinates": [
-99.965556000000007,
37.763333000000003
]
}
},
-- 开始代码--
d3.json("airports.json", function(collection) {
var bounds = d3.geo.bounds(collection),
path = d3.geo.path().projection(project);
path.pointRadius(5);
var locations = g.selectAll("path")
.data(collection.features, function(d) {
if(d.state == "KS"){
console.log(d.state);
return d.state;
}
})
.enter()
.append("path")
.attr("opacity", 100);
最佳答案
你要做的是array.filter ,然后将其传递给 data() 方法。
例如(您的代码非常接近!)
var locations = g.selectAll("path")
.data(collection.features.filter(function(d) {
return d.state == "KS";
})
.enter()
...
查看 Arrays 上的 d3 API 文档- 它很好地突出了 d3.js 数组功能和常用的内置 javascript 数组功能。
关于javascript - 在 D3.js 中迭代 geojson 并在满足条件时返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13655903/