jQuery: How to count result from JSON

57
February 21, 2019, at 03:00 AM

I am returning a JSON array for a project. Here's what the response looks like:

{"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: []

I am trying to return a function that will count how many of the results have users_todos -> status_id = 'value' and then put that into a label elsewhere on the page.

Here's what I have so far:

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']) + ')');

I am currently getting a count of 0 for all _count values. It seems like I'm missing the proper way to detect the status_id values from the JSON response.

Answer 1

You can use array filter method , which will return an array of matched elements. Then use length property to get the value

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'))

Answer 2

Well, to count all rows that have user_todos you need another function like this one:

function count_all(json) {
  return json.filter(function(row) {
    return row.users_todos).length;
  }
}
Answer 3

A. You need iterate only "data" 's children ("options" and "files" stay out)

B. The child of "data" is an array

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

Assuming you parse your JSON into a JavaScript object first, then your code should work - it will return 1 for the first count, which is correct based on the sample data provided.

Just ensure you used JSON.parse() to import the JSON first, otherwise you're dealing with a string, and not an object.

function count_category(category, json) { 
 
  var count = 0; 
  $.each(json, function(k, v) { 
    if (v['users_todos']['status_id'] === category) { 
      count++; 
    } 
  }); 
 
  return count; 
 
}; 
 
var rawjson = '{"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":[]}'; 
 
var json = JSON.parse(rawjson); 
 
console.log('(' + count_category('0', json['data']) + ')'); 
console.log('(' + count_category('1', json['data']) + ')'); 
console.log('(' + count_category('2', json['data']) + ')'); 
console.log('(' + count_category('3', json['data']) + ')');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you fail to parse the JSON and just run your code against the raw JSON string, it produces 0 for all counts, as you reported in your question.

N.B. There are definitely more efficient ways to achieve what you're trying to do, but my point is that there's nothing inherently broken about your code, apart from possibly not parsing your JSON.

READ ALSO
node.js mssql: Error: Global connection already exists. Call sql.close() first

node.js mssql: Error: Global connection already exists. Call sql.close() first

I have the following code based on this documentation:

51
ExpressJS: Always prints out the error in the console, NODE_ENV set to production

ExpressJS: Always prints out the error in the console, NODE_ENV set to production

Can anyone helpI am throwing errors from my application in express

63
NPM, should build-time dependencies be placed under dev-dependencies or dependencies?

NPM, should build-time dependencies be placed under dev-dependencies or dependencies?

I'm working on a node server that I want to deploy on HerokuTo keep it simple, I'm using Heorku's 'automatic deploys from master' option; whenever I push a change to GitHub, the Heroku app will update

44
How to defend against xss when saving data and when displaying it

How to defend against xss when saving data and when displaying it

Let's say I have a simple CRUD application with a form to add new object and edit an existing oneFrom a security point of view I want to defend against cross-site scripting

11