我有一个以下结构的geojson
文件:
var areas = {
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "id": 0, "properties": { "name": "a", "count": "854" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 13.271687552328165, 29.359549285088008 ], [ 13.272222904657671, 29.357697459147403 ], [ 13.272586765837973, 29.35566049412985 ], [ 13.273062097784726, 29.354438105832578 ], [ 13.272652418199639, 29.360795108476978 ], [ 13.271320041078822, 29.360700647951568 ], [ 13.271687552328165, 29.359549285088008 ] ] ] } }
,
{ "type": "Feature", "id": 1, "properties": { "name": "b", "count": "254"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 13.277038163109875, 29.358442424220023 ], [ 13.276782949188294, 29.358122923383512 ], [ 13.275290999273452, 29.358508600578681 ], [ 13.274634727185679, 29.358485484466968 ], [ 13.282581930993208, 29.358635779719847 ], [ 13.278334024184868, 29.359814295404375 ], [ 13.277038163109875, 29.358442424220023 ] ] ] } }
,
{ "type": "Feature", "id": 2, "properties": {"name": "c", "count": "385"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 13.279484097462499, 29.349831113628788 ], [ 13.27792879702741, 29.349728966688758 ], [ 13.276089401418951, 29.349901260351807 ], [ 13.275677565886326, 29.349951087700632 ], [ 13.279484097462499, 29.349831113628788 ] ] ] } }
,
{ "type": "Feature", "id": 3, "properties": { "name": "d", "count": "243"}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 13.290520299215724, 29.352306689134622 ], [ 13.289722088408338, 29.351802774685929 ], [ 13.289065241087885, 29.352101541350635 ], [ 13.28785814146197, 29.351114667998772 ], [ 13.290520299215724, 29.352306689134622 ] ] ] } }
]
}
通常,要将此数据转换为数组,我将创建一个循环来运行将该值存储在数组中的相应变量。但是,我不知道这是否是最佳方法。有没有办法将id
的所有值都拉出到一个数组中,这样我最终会得到:
[0,1,2,3]
我很高兴使用任何外部库来做到这一点 - 如果有一种比我目前的方法更有效的方式,我很好奇。
答案 0 :(得分:1)
如果你绝对不顾一切地去做其他事情,你可以试试underscore's map。代码看起来像这样:
_.map(areas.features, function (item) { return item.id });
这将调用要素中每个项目的内部函数,并返回包含每个结果的数组。
我不认为你可以在这里做任何过于激进的事情 - 最终,从嵌套对象和数组中提取值不能太过愚蠢。
答案 1 :(得分:1)
不是我的代码,但是这里有关于从json非常有效地获取值的帖子。
参考帖子 use jQuery's find() on JSON object
用户Box9的回答可能是最好的方法
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
关于这个代码块也赞成了这个答案,因为它是关于我发现提取值的最好方法
答案 2 :(得分:1)
这样的事情应该有效:
var arr = new Array();
for(var i = 0; i < areas.features.length; i++){
arr.push(areas.features[i].id)
}
要直接获得某个id
值,您可以执行以下操作:
areas.features[0].id
在这种情况下将是0
。
<强> EXAMPLE 强>