2014-09-29 71 views
2

注:有人指出,已經提出了一些可能的解決方案here。然而,.map正好我正在尋找,並沒有出現在那個其他全面的職位。托馬斯的答案涵蓋了我的用例。如何從單個GeoJSON屬性創建一個數組值?

使用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的性質(即列),從而深深嵌套我還沒有任何運氣.map,我想避免循環,但我會採取任何事情在這一點上。

上下文是,我希望能夠從連接到我映射的要素的每個「變量」中提取分配信息,對於example

+0

通過「任意」,你的意思是「隨機」? – Bergi 2014-09-29 00:40:10

+0

我不明白爲什麼'responseData.features.map(function(f){return f.properties.beverage})'不起作用。你究竟做了什麼? – Bergi 2014-09-29 00:41:33

+0

我沒有使用函數結構(即我這樣做:'responseData.features.map.properties.beverage')。你是完全正確的。 – 2014-09-29 01:06:55

回答

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調用的到來,因此它在第一個字符串,中庸之道使用JSON.parse(yourGeoJSON)

+0

完美,托馬斯。謝謝! – 2014-09-29 01:08:05

相關問題