1

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") );
1
  • Did you check some of them posted answer or waiting for new one Commented Jul 18, 2014 at 6:07

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't realize I needed to add [0]...I figured it had to do with the fact that it was an array but I just never bothered to try that!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.