我在这个网站上搜索了很多例子,但似乎无法满足我的需求。我只需要使用grep()
过滤一些JSON结果。
以下是我的JSON:
var data = { "items": [
{
"id": 1,
"category": "cat1"
},
{
"id": 2,
"category": "cat2"
},
{
"id": 3,
"category": "cat1"
}
]}
以上例子
cat1
?cat1
且id
为3的商品?我知道这不是一个很好的例子,但任何帮助都会很棒!谢谢!
我尝试了以下
的变体data.items = $.grep(data.items, function(element, index) {
return element.id == 1;
console.log(data.items);
});
答案 0 :(得分:49)
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返回一个对象数组,因此您可以通过数组索引访问它。
答案 1 :(得分:0)
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}, {
"id": 4,
"category": "cat2"
}, {
"id": 5,
"category": "cat1"
}]
};
//Filters an array of numbers to include only numbers bigger then zero.
//Exact Data you want...
var returnedData = $.grep(data.items, function(element) {
return element.category === "cat1" && element.id === 3;
}, false);
console.log(returnedData);
$('#id').text('Id is:-' + returnedData[0].id)
$('#category').text('Category is:-' + returnedData[0].category)
//Filter an array of numbers to include numbers that are not bigger than zero.
//Exact Data you don't want...
var returnedOppositeData = $.grep(data.items, function(element) {
return element.category === "cat1";
}, true);
console.log(returnedOppositeData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id='id'></p>
<p id='category'></p>
$.grep()
方法会根据需要从数组中删除项目,以便只有其余项目才能进行给定的搜索。测试是一个传递数组项和数组中项索引的函数。仅当测试返回true时,该项才会在结果数组中。