使用jQuery.grep()过滤数据

时间:2015-10-27 13:21:39

标签: javascript jquery

我想过滤存储在.js中的数据。我尝试了jQuery.grep()方法*,但每个数据仍在加载。

数据

var myData = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": {"name": urn:ogc:def:crs:OGC:1.3:CRS84"},
"features": [    
{ "type": "Feature", "properties": { "id": 11, "type": "capitale", "pays": "pas fr", "nom": "berlin" }, "geometry": { "type": "Point", "coordinates": [ 13.395132552297285, 52.508943107353431 ] } },
{ "type": "Feature", "properties": { "id": 10, "type": "capitale", "pays": "pas fr", "nom": "amsterdam" }, "geometry": { "type": "Point", "coordinates": [ 4.855651367625091, 52.394023028252583 ] } },
{ "type": "Feature", "properties": { "id": 9, "type": "capitale", "pays": "pas fr", "nom": "londres" }, "geometry": { "type": "Point", "coordinates": [ -0.141426738862896, 51.509964983366203 ] } },
{ "type": "Feature", "properties": { "id": 8, "type": "capitale", "pays": "pas fr", "nom": "bruxelles" }, "geometry": { "type": "Point", "coordinates": [ 4.323617445236209, 50.851394650375276 ] } },
{ "type": "Feature", "properties": { "id": 7, "type": "ville", "pays": "france", "nom": "dijon" }, "geometry": { "type": "Point", "coordinates": [ 5.050954959388099, 47.311364936576716 ] } },
{ "type": "Feature", "properties": { "id": 6, "type": "ville", "pays": "france", "nom": "clermont-ferrand" }, "geometry": { "type": "Point", "coordinates": [ 3.13832668143313, 45.876878693687296 ] } },
{ "type": "Feature", "properties": { "id": 5, "type": "ville", "pays": "france", "nom": "lyon" }, "geometry": { "type": "Point", "coordinates": [ 4.848916761012574, 45.7642371486427 ] } },
{ "type": "Feature", "properties": { "id": 4, "type": "capitale", "pays": "france", "nom": "paris" }, "geometry": { "type": "Point", "coordinates": [ 2.316704674705995, 48.867681379583189 ] } },
{ "type": "Feature", "properties": { "id": 3, "type": "ville", "pays": "france", "nom": "montpellier" }, "geometry": { "type": "Point", "coordinates": [ 3.91954104848516, 43.619755259636626 ] } },
{ "type": "Feature", "properties": { "id": 2, "type": "ville", "pays": "france", "nom": "toulouse" }, "geometry": { "type": "Point", "coordinates": [ 1.414267388628651, 43.600250453043067 ] } },
{ "type": "Feature", "properties": { "id": 1, "type": "ville", "pays": "france", "nom": "rennes" }, "geometry": { "type": "Point", "coordinates": [ -1.670182439904363, 48.153851807885481 ] } }
]
};

功能

var myFilter = $.grep(myData.features, function (element, index) {
            return element.properties.pays == "france";
        });

        for (var i=0;i<myFilter.length;i++) {
            alert(myFilter[0].properties.pays + "  " + myFilter[0].properties.nom);
        };

这种语法有问题,但我不知道在哪里。

1 个答案:

答案 0 :(得分:0)

element没有字段pays。您需要使用element.properties

var myFilter = $.grep(myData.features, function (element, index) {
    return element.properties.pays == "france";
});
相关问题