jQuery:如何计算JSON的结果

chr*_*age 0 javascript jquery

我正在为项目返回一个JSON数组.这是响应的样子:

{"data":[{"DT_RowId":"row_60","contacts":{"first_name":"Screech","last_name":"Powers"},"users_todos":{"text":"whowho","due_date":"Wed, Feb 6 2019","company_id":"1","location_id":"15","assigned_to_user_id":"21","assigned_to_contact_id":"4258","inserted_by_user_id":"15","status_id":"0"}}],"options":[],"files":[]}


data: [{DT_RowId: "row_60", contacts: {first_name: "Screech", last_name: 
     "Powers"},…}]
   0: {DT_RowId: "row_60", contacts: {first_name: "Screech", last_name: 
     "Powers"},…}
      DT_RowId: "row_60"
      contacts: {first_name: "Screech", last_name: "Powers"}
           first_name: "Screech"
           last_name: "Powers"
      users_todos: {text: "whowho", due_date: "Wed, Feb 6 2019", company_id: 
       "1", location_id: "15",…}
            assigned_to_contact_id: "4258"
            assigned_to_user_id: "21"
            company_id: "1"
            due_date: "Wed, Feb 6 2019"
            inserted_by_user_id: "15"
            location_id: "15"
            status_id: "0"
            text: "whowho"
   files: []
   options: []
Run Code Online (Sandbox Code Playgroud)

我正在尝试返回一个函数,该函数将计算有多少结果包含users_todos - > status_id ='value',然后将其放入页面上其他位置的标签中.

这是我到目前为止所拥有的:

function count_category(category, json) {

var count= 0;
$.each(json, function (k , v) {
    if (v['users_todos']['status_id'] === category) {
        count++;
    }
});

return count;

};

$('.user_todos_incomplete_count').text('(' + count_category('0', json['data']) + ')');

$('#user_todos_in_progress_count').text('(' + count_category('1', json['data']) + ')');

$('#user_todos_complete_count').text('(' + count_category('2', json['data']) + ')');

$('#user_todos_disregarded_count').text('(' + count_category('3', json['data']) + ')');
Run Code Online (Sandbox Code Playgroud)

我目前所有_count值的计数为0.好像我错过了从JSON响应中检测status_id值的正确方法.

brk*_*brk 5

您可以使用数组过滤器方法,该方法将返回匹配元素的数组.然后使用lengthproperty获取值

let dt = {
  "data": [{
    "DT_RowId": "row_60",
    "contacts": {
      "first_name": "Screech",
      "last_name": "Powers"
    },
    "users_todos": {
      "text": "whowho",
      "due_date": "Wed, Feb 6 2019",
      "company_id": "1",
      "location_id": "15",
      "assigned_to_user_id": "21",
      "assigned_to_contact_id": "4258",
      "inserted_by_user_id": "15",
      "status_id": "0"
    }
  }],
  "options": [],
  "files": []
}


function getCount(cat) {
  return dt.data.filter(elem => elem.users_todos.status_id === cat).length

}

console.log(getCount('0'))
Run Code Online (Sandbox Code Playgroud)