1

我有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]

我也很乐意使用任何外部库来做到这一点——我主要是好奇是否有比我目前的方法更有效的方法。

4

3 回答 3

1

如果您绝对不顾一切尝试其他方法,可以尝试underscore 的 map。代码看起来像这样:

_.map(areas.features, function (item) { return item.id });

这将调用 features 中每个项目的内部函数,并返回一个包含每个结果的数组。

我不认为你可以在这里做任何过于激进的事情 - 最终,从嵌套对象和数组中提取值不能被简化太多。

于 2012-10-04T18:17:23.680 回答
1

不是我的代码,但这里有一篇关于非常有效地从 json 获取值的帖子。

请参阅 在 JSON 对象上使用 jQuery 的 find()后

User 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;
}

关于这个代码块也支持这个答案,因为它是我发现提取值的最佳方式

于 2012-10-04T18:17:40.380 回答
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.

例子

于 2012-10-04T18:18:00.413 回答