TheIntrepidSpiff
TheIntrepidSpiff

Reputation: 189

How to query a JSON array with jQuery

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") );

Upvotes: 1

Views: 492

Answers (2)

Balachandran
Balachandran

Reputation: 9637

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 array

 var count = 0;

    function countTypesForBulan(post) {
        $.each(post, function (j, val2) {
            if (val2.custom_fields.hasOwnProperty('us_congress_chamber') && $.inArray("senate", val2.custom_fields.us_congress_chamber) != -1) {

               // do your work or change anything if condition is satisfied 
                count++;
            }
        });
        return count;
    }

DEMO

Upvotes: 1

jogesh_pi
jogesh_pi

Reputation: 9782

it is because

// return object
resultArray[i].custom_fields.us_congress_chamber

return and object that is not equal to "senate" that should be

// return string value
resultArray[i].custom_fields.us_congress_chamber[0]

here is your complete code

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[0] === bulanVal &&
         !types[resultArray[i].id]) {
           types[resultArray[i].id] = true;
           count++;
    }
  }
  return count;
}

Upvotes: 1

Related Questions