Adam Stelle
Adam Stelle

Reputation: 39

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"

Upvotes: 1

Views: 2094

Answers (4)

neojg
neojg

Reputation: 221

Just to be sure that I understand your question let consider the following inefficient straightforward implementation:

var data = [{address:"9001 Lake...", ..., type:"Medic Response"}, 
            {address:"...", ..., type:"Aid Response",
            ...,
            {address""...", ..., type:"Medic Response"}];
var i, j, b, result = [] ;
for(i = 0; i < data.length; i ++)
{
    b = false ;
    for(j = 0; j < result.length; j++)
       if(result[j].key == data.type) {
           result[j].count += 1 ;
           b = true ;
           break ;
       }
     if (!b) {
        result.push({key:data.type, count: 1});
     }
}
// result is the frequency array of the "type" values in data array

Upvotes: 0

vp_arth
vp_arth

Reputation: 14982

You can use reduce also:

objs.reduce(function(c, d){
  if (!c[d.type]) c[d.type] = 0;
  c[d.type]++;
  return c;
}, {});

Upvotes: 0

ste2425
ste2425

Reputation: 4766

You could use array.reduce to reduce your data array into an object map.

That is assuming its a flat array of objects and your not nesting things.

var count = data.reduce(function(prev, cur) {
  if (prev.hasOwnProperty(cur.type))
    prev[cur.type] += 1;
  else
    prev[cur.type] = 1;

  return prev;
}, {});

see fiddle reduce docs

Upvotes: 1

Nicholas Cloud
Nicholas Cloud

Reputation: 1574

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

Upvotes: 3

Related Questions