在导入时从json创建键值对

时间:2017-06-04 19:17:46

标签: javascript jquery json ajax geojson

我是jquery的新手 - 我有一个有效的geojson文件,我想访问features并将其转换为键值对的对象。我的目标是仅使用properties.cat作为键,使用properties.name作为值(可以忽略所有其他数据)。这是一个示例:

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },
"features": [
{ "type": "Feature", "properties": { "cat": "A", "name": "Aberdeen"}, "geometry": { "type": "Point", "coordinates": [ 16.37208, 48.20849 ] } },
{ "type": "Feature", "properties": { "cat": "B", "name": "Berlin"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
{ "type": "Feature", "properties": { "cat": "C", "name": "Copenhagen"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
{ "type": "Feature", "properties": { "cat": "D", "name": "Dublin" }, "geometry": { "type": "Point", "coordinates": [ 12.56553, 55.67594 ] } },
{ "type": "Feature", "properties": { "cat": "E", "name": "Edinburgh"}, "geometry": { "type": "Point", "coordinates": [ -3.7037902, 40.4167754 ] } }
]
}


  $.getJSON("sample.geojson", function(json) {

    console.log(json.features[0].properties.cat);

      });

如下所述,features是一个数组。 如何直接从json中的每个要素属性创建键值对的对象,以便具有以下输出:

{A : Aberdeen, B: Berlin, C: Copenhagen, D: Dublin, E: Edinburgh}

1 个答案:

答案 0 :(得分:1)

$.getJson方法的回调函数已经自动解析了响应。

此外,功能对象是一个数组。使用此:

console.log(json.features[0].properties.cat);

要制作键值对,您可以使用reduce方法,该方法接受为每个项目应用callback提供的方法。



var json= {
      "type": "FeatureCollection",
      "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },
      "features": [
      { "type": "Feature", "properties": { "cat": "A", "name": "Aberdeen"}, "geometry": { "type": "Point", "coordinates": [ 16.37208, 48.20849 ] } },
      { "type": "Feature", "properties": { "cat": "B", "name": "Berlin"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
      { "type": "Feature", "properties": { "cat": "C", "name": "Copenhagen"}, "geometry": { "type": "Point", "coordinates": [ 4.3517103, 50.8503396 ] } },
      { "type": "Feature", "properties": { "cat": "D", "name": "Dublin" }, "geometry": { "type": "Point", "coordinates": [ 12.56553, 55.67594 ] } },
      { "type": "Feature", "properties": { "cat": "E", "name": "Edinburgh"}, "geometry": { "type": "Point", "coordinates": [ -3.7037902, 40.4167754 ] } }
      ]
}
var obj=json.features.reduce(function(obj,item){
  obj[item.properties.cat]=item.properties.name;
  return obj;
},{});
console.log(obj);