mercredi 16 décembre 2015

Count unique elements from JSON array taking 2 different Keys into consideration - Javascript

I have the following JSON array, which contains all the available metrics and dimensions from the Google Analytics API v3:

http://ift.tt/1IUUOqQ

I want to make a table which includes the number of dimensions and the number of metrics. I can get this information with the following code:

var results = new Array();
for (var j = 0; j < output.items.length; j++) {
    var key = output.items[j].attributes.type.toString(); // make it an associative array 
    if (!results[key]) { 
        results[key]=1 
    } else { 
        results[key]=results[key] + 1; 
    } 
}

The result is: [DIMENSION: 244, METRIC: 206]

However, I would like to also obtain information of how many of these dimensions and metrics are public, deprecated or any other status that Google may give them in the future.

I assume there is a way to combine this information (type + status) in a single loop and array, but I am trying to obtain the status of the dimensions with the following code:

var statusDimensions = new Array();
for (var j=0; j<output.items.length; j++) {
    var key = output.items[j].attributes.type.toString(); // make it an associative array
    var subKey = output.items[j].attributes.status.toString(); // make it an associative array
    if (key != "METRIC" && !statusDimensions[subKey]) {
        statusDimensions[subKey] = 1
    } else {
        statusDimensions[subKey] = statusDimensions[subKey] + 1;
    }
}

However, the result is: [PUBLIC: 414, DEPRECATED: 36], which denotes that the evaluation of the if condition key != "METRIC" is not doing what I am expecting.

  1. Why is this happening? I can't determine the cause
  2. How could I obtain an Array which include both information (type + status) in an unique loop?

Aucun commentaire:

Enregistrer un commentaire