Filtering JSON array using jQuery grep()
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>
The $.grep()
method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.
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);
The returnedData is returning an array of objects, so you can access it by array index.
http://jsfiddle.net/wyfr8/913/