This question already has answers here:
How can I access and process nested objects, arrays or JSON?
                                
                                    (22个答案)
                                
                        
                                5年前关闭。
            
                    
注意:已经指出,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时,属性(即列)是如此的嵌套,以至于我对.map没有任何运气,并且我想避免循环,但是现在我会采取任何措施。

上下文是,我希望能够从example的每个映射到要素的“变量”中提取分布信息。

最佳答案

尝试如下

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)

09-11 19:06
查看更多