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]++
}
});
USE len() TO COUNT THE ITEMS IN A JSON OBJECT. Call len(obj) to return the number of items in a JSON object obj.
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.
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.
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.
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
javascript for
loop is fastest:
var counter = 0;
for (var i = 0; i < data.humans.length; i++) {
if (data.humans[i].hairs === 2) {
counter++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With