[英]Filter JSON data using $getJSON
I have the following code, which is loading in the full JSON file.我有以下代码,它正在加载完整的 JSON 文件。
$.getJSON("data/Data1.json", function (data) {
currentStatus.addData(data);
map.addLayer(currentStatusLayer);
});
What I am trying to do is filter the JSON file, but am struggling to get only the filtered value from the JSON data record.我想要做的是过滤 JSON 文件,但我正在努力只从 JSON 数据记录中获取过滤后的值。
What I am trying to get is the record which has 'Status: Watch'.我想要获得的是具有“状态:观看”的记录。
Here is my code below:下面是我的代码:
$.getJSON("data/Data1.json", function (data) {
currentStatus = data.features.filter(function(feature) {
return feature.status === 'Watch';
});
currentStatus.addData(data);
map.addLayer(currentStatusLayer);
});
Trimmed down JSON data file:删减 JSON 数据文件:
[
{
"type": "Feature",
"id": 0,
"status": "watch",
"properties": {
"NAME": "Watch Test"
}
},
{
"type": "Feature",
"id": 1,
"status": "act",
"properties": {
"NAME": "Act Test"
}
}
]
Thank you谢谢
filter
will remove item(s) based on your criteria from the features array. filter
将根据您的条件从 features 数组中删除项目。
I believe you would like to use find in order to find item in your array of features:我相信您想使用find来查找您的一系列功能中的项目:
currentStatus = data.features.find(function(feature) {
return feature.status.toLowerCase() === 'watch';
}
Please keep in mind, that find
method returns the value of the first element in the provided array.请记住,
find
方法返回所提供数组中第一个元素的值。
Pro tip: convert your status
property with toLowerCase()
method to make sure that you are comparing case agnostic strings.专业提示:使用
toLowerCase()
方法转换您的status
属性,以确保您正在比较不区分大小写的字符串。
You could always use filter like this:你总是可以像这样使用过滤器:
$.getJSON("data/Data1.json", function (data) {
///set your variable - you did this part right:
var items = data;
// now apply your filter:
items = data.filter(function(obj) {
// return the filtered value
return obj.status ==="watch";
});
// verify in your console:
console.log(items);
// continue with your project ;)
currentStatus.addData(items);
map.addLayer(currentStatusLayer);
});
This should work for your filtering.这应该适用于您的过滤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.