2017-06-04 63 views
0

我是jquery的新手 - 我有一個有效的geojson文件,它的features我想訪問並轉換爲鍵值對的對象。我的目標是隻使用properties.cat作爲關鍵字,而properties.name作爲值(所有其他數據可以忽略)。下面是一個示例:在導入時從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 ] } } 
] 
} 


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

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

     }); 

正如以下指出的那樣,features是一個數組。 怎會直接從每個創建鍵值對的對象在JSON功能特性使其具有以下輸出:

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

你嘗試了JSON解析可變它之前登錄到控制檯? – Botimoo

+0

var obj是什麼? – RohitS

+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);

+0

謝謝,我編輯了我的問題 –

+0

@the_darkside,看看更新的答案。 –

+0

謝謝@Alexandru,但是當我用getJSON包裝它時,它不起作用:'$ .getJSON(「sample.geojson」,function(json){varilla = {}; json.features.reduce(function(obj,項){ OBJ [item.properties.cat] = item.properties.name; 返回物鏡; },{}); 的console.log(OBJ) });' –