Javascript 使用$getJSON筛选JSON数据
我有以下代码,加载到完整的JSON文件中Javascript 使用$getJSON筛选JSON数据,javascript,jquery,json,Javascript,Jquery,Json,我有以下代码,加载到完整的JSON文件中 $.getJSON("data/Data1.json", function (data) { currentStatus.addData(data); map.addLayer(currentStatusLayer); }); 我试图做的是过滤JSON文件,但我很难从JSON数据记录中获得过滤后的值 我想得到的是“状态:手表”的记录 下面是我的代码: $.getJSON("data/Data1.json"
$.getJSON("data/Data1.json", function (data) {
currentStatus.addData(data);
map.addLayer(currentStatusLayer);
});
我试图做的是过滤JSON文件,但我很难从JSON数据记录中获得过滤后的值
我想得到的是“状态:手表”的记录
下面是我的代码:
$.getJSON("data/Data1.json", function (data) {
currentStatus = data.features.filter(function(feature) {
return feature.status === 'Watch';
});
currentStatus.addData(data);
map.addLayer(currentStatusLayer);
});
精简JSON数据文件:
[
{
"type": "Feature",
"id": 0,
"status": "watch",
"properties": {
"NAME": "Watch Test"
}
},
{
"type": "Feature",
"id": 1,
"status": "act",
"properties": {
"NAME": "Act Test"
}
}
]
谢谢
过滤器将根据您的条件从功能阵列中删除项目
我相信您希望使用以下选项,以便在功能阵列中查找项目:
currentStatus=data.features.find(函数(特征)){
返回feature.status.toLowerCase()=='watch';
}
请记住,find
方法返回所提供数组中第一个元素的值
专业提示:使用toLowerCase()
方法转换status
属性,以确保比较不区分大小写的字符串。您始终可以使用如下筛选器:
$.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);
});
这对您的筛选应该有用。谢谢Andrew。但是,我得到的控制台错误不是一个函数:currentStatus.addData(data);很难说没有剩下的代码,但你可以尝试用我上面的代码片段替换依赖于过滤器的当前代码,该代码片段正在使用findThank you再次感谢Andrew。你的想法促使了我的方法,我提出了一个适合我的项目的解决方案。祝你愉快。