I’m trying to search and JSON output from my WordPress site, in order to get the number of posts that have a specific custom field value.
For instance, here’s some JSON output:
{"posts":[
{
"id": 21831,
"custom_fields": {
"us_congress_chamber": [
"senate"
]
}
},
{
"id": 21830,
"custom_fields": {
"us_congress_chamber": [
"senate"
]
}
}]}
I want to count how many entries have the custom_fields=us_congress_chamber and us_congress_chamber=senate, but this is the best I could come up with from another post on SO, but it just gives 0
var json = '{"posts":[{"id": 21831,"custom_fields":{"us_congress_chamber": ["senate"]}},{"id": 21830,"custom_fields": {"us_congress_chamber": ["senate"]}}]}';
var obj = JSON.parse(json);
function countTypesForBulan(resultArray, bulanVal) {
var i,
types,
count = 0;
for (i=0, types = {}; i < resultArray.length; i++)
if (resultArray[i].custom_fields.us_congress_chamber === bulanVal && !types[resultArray[i].id]) {
types[resultArray[i].id] = true;
count++;
}
return count;
}
alert( countTypesForBulan(obj.posts, "senate") );
it is because
return and object that is not equal to
"senate"
that should behere is your complete code
Use
.each
method in query ,hasOwnProperty
to check is having property of us_congress_chamber or not.$.inArray()
use to check the given value is in or not in the arrayDEMO