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);
});
The grep() method finds an element and the filter() method returns elements matching a specific criteria.
To filter JSON data with multiple objects, you can use the concept of filter along with ==.
The grep() method in jQuery finds the array elements that satisfy the given filter function. It does not affect the original array. This method returns the filtered array, i.e., the elements that satisfy the given filter function.
Use the JSON filter if your trigger receives JSON-encoded data. JSON filter allows you to use variables and values from your JSON file. The filter supports data extraction from JSON arrays. Automation allows you to use all JSON data types.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With