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()
.
Below is my JSON:
var data = { "items": [
{
"id": 1,
"category": "cat1"
},
{
"id": 2,
"category": "cat2"
},
{
"id": 3,
"category": "cat1"
}
]}
With the example above
cat1
?cat1
and id
of 3 ?I know this isn't a great example but any help would be awesome! Thanks!
I have tried variations of the following
data.items = $.grep(data.items, function(element, index) {
return element.id == 1;
console.log(data.items);
});
var data = {_x000D_
"items": [{_x000D_
"id": 1,_x000D_
"category": "cat1"_x000D_
}, {_x000D_
"id": 2,_x000D_
"category": "cat2"_x000D_
}, {_x000D_
"id": 3,_x000D_
"category": "cat1"_x000D_
}, {_x000D_
"id": 4,_x000D_
"category": "cat2"_x000D_
}, {_x000D_
"id": 5,_x000D_
"category": "cat1"_x000D_
}]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
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.
Source: Stackoverflow.com