Adam Stelle Adam Stelle - 5 months ago 12
JSON Question

Counting instances of key value pairs in JSON file in JavaScript

I'm working with a large dataset of objects with a number of attributes (see below) and trying to count the number of instances of each "type" attribute. The hard part is that there are a large # of different types, so I can't start with a predefined list.

So, the ideal output from the below data would be:

"Medic Response" : 2
"Aid Response" : 1


Thanks in advance.

Object

address: "9001 Lake City Way Ne"
datetime : "2011-02-12T18:04:00.000"
incident_number : "F110013072"
latitude :"47.693931"
longitude : "-122.30552"
type : "Medic Response"


Object

address : "97 S Main St"
datetime : "2011-02-16T18:46:00.000"
incident_number : "F110014403"
latitude : "47.600044"
longitude : "-122.334219"
type : "Aid Response"


Object

address : "509 3rd Av"
datetime : "2011-02-12T07:30:00.000"
incident_number : "F110012897"
latitude : "47.602114"
longitude : "-122.330809"
report_location :
type : "Medic Response"

Answer

You can use a key/value hash of type names/counts, and then iterate over your collection of objects, incrementing each count as you go. For example:

var counts = {};
var objects = [/*array of your objects*/];

objects.forEach(function (o) {
    // add the type to the hash if it is missing;
    // set initial count to 0
    if (!counts.hasOwnProperty(o.type)) {
        counts[o.type] = 0;
    }
    // increment the count based on the type
    counts[o.type] += 1;
});

console.log(counts);
Comments