Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of elements with certain properties inside JSON

I have some JSON data:

{"humans": [
    { "firstName" : "Paul", "lastName" : "Taylor", "hairs": 2 },
    { "firstName" : "Sharon", "lastName" : "Mohan", "hairs": 3 },
    { "firstName" : "Mohan", "lastName" : "Harris", "hairs": 3 },
    { "firstName" : "Deborah", "lastName" : "Goldman", "hairs": 4 },
    { "firstName" : "Mark", "lastName" : "Young", "hairs": 4 },
    { "firstName" : "Tom", "lastName" : "Perez", "hairs": 4 }
    //and so on...
]}

I want to be able to count all people with 2 hairs, 3 hairs etc. Right now I am using jQuery.each() plus an incrementing count-array which works fine. But I was wondering if there is an easier way to do this.

UPDATE: Additional code saying what I am doing right now:

var results = eval(data.humans);
var count_array = [0, 0, 0, 0, 0, 0, 0];
$(results).each(function() {
    if (this.hairs == 1) {
        count_array[0]++;
    }
    if (this.hairs == 2) {
        count_array[1]++
    }
    if (this.hairs == 3) {
        count_array[2]++
    }
    if (this.hairs == 4) {
        count_array[3]++
    }
    if (this.hairs == 5) {
        count_array[4]++
    }
    if (this.hairs == 6) {
        count_array[5]++
    }
    if (this.hairs == 7) {
        count_array[6]++
    }
});
like image 764
Mohit Avatar asked May 04 '15 08:05

Mohit


People also ask

How do I count the number of elements in JSON?

USE len() TO COUNT THE ITEMS IN A JSON OBJECT. Call len(obj) to return the number of items in a JSON object obj.

How do you count the number of properties in an object?

keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.

Can you do calculations in JSON?

No, it isn't possible to do math or any kind of expression in JSON as JSON is just a data structure format, and not a programming language. You will need to load the JSON data in using a programming language of your choice, at which point you can then manipulate it.

What is forEach in JSON?

The fetch function retrieves data as JSON array from the provided URL. With forEach , we go through the array. Object. entries(obj). forEach(([key, value]) => { console.


2 Answers

You can use the filter function to filter an array of objects :

var data = {...}

data.humans.filter(function(o) { return o.hairs == 2 }).length
//Return the number of humans who have 2 hairs

Take a look fiddle

like image 96
jmgross Avatar answered Oct 23 '22 12:10

jmgross


javascript for loop is fastest:

var counter = 0;

for (var i = 0; i < data.humans.length; i++) {
   if (data.humans[i].hairs === 2) {
      counter++;
   }
}
like image 26
freethinker Avatar answered Oct 23 '22 12:10

freethinker