使用 jQuery grep() 过滤 JSON 数组 [英] Filtering JSON array using jQuery grep()
本文介绍了使用 jQuery grep() 过滤 JSON 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在本网站上搜索了许多示例,但似乎无法满足我的需求.我只需要使用 grep()
过滤一些 JSON 结果.
I've searched many examples on this site but can't seem to fit them into my needs. I just need to filter some JSON results using grep()
.
以下是我的 JSON:
Below is my JSON:
var data = { "items": [
{
"id": 1,
"category": "cat1"
},
{
"id": 2,
"category": "cat2"
},
{
"id": 3,
"category": "cat1"
}
]}
以上面的例子
- 我将如何返回类别为
cat1
的所有项目? - 如何返回类别为
cat1
且id
为 3 的所有项目?
- how would I return all items with the category of
cat1
? - how would I return all items with the category of
cat1
andid
of 3 ?
我知道这不是一个很好的例子,但任何帮助都会很棒!谢谢!
I know this isn't a great example but any help would be awesome! Thanks!
我尝试了以下变体
data.items = $.grep(data.items, function(element, index) {
return element.id == 1;
console.log(data.items);
});
推荐答案
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
returnedData 返回一个对象数组,因此您可以通过数组索引访问它.
The returnedData is returning an array of objects, so you can access it by array index.
http://jsfiddle.net/wyfr8/913/
这篇关于使用 jQuery grep() 过滤 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文