如何使用jQuery查询JSON数组

时间:2014-07-18 05:16:46

标签: jquery json wordpress

我正在尝试从我的WordPress网站搜索和输出JSON,以获取具有特定自定义字段值的帖子数。

例如,这里有一些JSON输出:

{"posts":[
{
  "id": 21831,
  "custom_fields": {
    "us_congress_chamber": [
      "senate"
    ]
  }
},
{
  "id": 21830,
  "custom_fields": {
    "us_congress_chamber": [
      "senate"
    ]
  }
}]}

我想计算有多少条目有custom_fields = us_congress_chamber和us_congress_chamber =参议院,但这是我从SO上的另一篇帖子中得到的最好的,但它只是给出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") );

2 个答案:

答案 0 :(得分:1)

这是因为

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

返回和不等于"senate"的对象

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

这是您的完整代码

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;
}

答案 1 :(得分:1)

在查询中使用.each方法,hasOwnProperty检查是否具有us_congress_chamber属性.$.inArray()用于检查给定值是否在数组中

 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