注意:有人指出已经提出了一些可能的解决方案here。但是,.map
完全我正在寻找的内容并没有出现在那个全面的帖子中。 Thomas的回答包括我的用例。
使用javascript,如何为GeoJSON文件中的每个要素创建一个表示任意属性值的值数组?我意识到我在这里失败了JSON 101,但我怎么能创建它:
['caiparinha','caucasian','margarita']
从这个?
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "brasil",
"beverage": "caiparinha"
},
"geometry": {
"type": "Point",
"coordinates": [
-56.953125,
-8.754794702435605
]
}
},
{
"type": "Feature",
"properties": {
"name": "russia",
"beverage": "caucasian"
},
"geometry": {
"type": "Point",
"coordinates": [
39.0234375,
57.136239319177434
]
}
},
{
"type": "Feature",
"properties": {
"name": "mexico",
"beverage": "margarita"
},
"geometry": {
"type": "Point",
"coordinates": [
-105.1171875,
25.165173368663954
]
}
}
]
}
如果源是CSV,那么就像从属性中选择/解析单个列一样简单,但是使用GeoJSON,属性(即列)是如此深层嵌套,以至于我没有运气{ {1}},我想避免循环,但此时我会采取任何措施。
上下文是我希望能够从example为我映射的要素附加的每个“变量”中提取分布信息。
答案 0 :(得分:2)
尝试以下内容
var geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "brasil",
"beverage": "caiparinha"
},
"geometry": {
"type": "Point",
"coordinates": [
-56.953125,
-8.754794702435605
]
}
},
{
"type": "Feature",
"properties": {
"name": "russia",
"beverage": "caucasian"
},
"geometry": {
"type": "Point",
"coordinates": [
39.0234375,
57.136239319177434
]
}
},
{
"type": "Feature",
"properties": {
"name": "mexico",
"beverage": "margarita"
},
"geometry": {
"type": "Point",
"coordinates": [
-105.1171875,
25.165173368663954
]
}
}
]
};
var expected_result = geojson.features.map(function (el) {
return el.properties.beverage;
});
console.log(expected_result);
如果您的GeoJSON来自Ajax调用,那么它首先是一个字符串,juste使用JSON.parse(yourGeoJSON)