Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ApoloSiskos/9fe4ff23405558bff3c7d31d99b0d03c to your computer and use it in GitHub Desktop.
Save ApoloSiskos/9fe4ff23405558bff3c7d31d99b0d03c to your computer and use it in GitHub Desktop.
Datorama JSON - Group by First Dimension convert to dictionary (array of objects) with Javascript
//Convert a Datorama JSON string to a dictionary (array of objects) and group by the first dimension (first key).
//Ideal for D3 charts. The output can be used to present the SUM of all Values (Second Dimension in this case) per Date (First Dimension)
////////////////////
//JSON query
var json_data = {"headers":["Month","Value","Number"],"rows":[["2018-10-01 00:00:00.0","one",209],["2018-09-01 00:00:00.0","one",274],["2018-09-01 00:00:00.0","five",183],["2018-10-01 00:00:00.0","five",164],["2018-09-01 00:00:00.0","four",214],["2018-10-01 00:00:00.0","four",192],["2018-09-01 00:00:00.0","three",128],["2018-10-01 00:00:00.0","three",125],["2018-09-01 00:00:00.0","two",199],["2018-10-01 00:00:00.0","two",169]]};
function groupBy(accumulator, item) {
//Pick the key (values included in the key)
const [date,extra,value] = item;
//It returns the substring of the date (excludes the day in this case)
const key = date.slice(0,7);
if(!accumulator[key]){
accumulator[key] = 0
}
accumulator[key] += value;
return accumulator;
}
var damn = json_data.rows.reduce(groupBy,{});
//Creates the new JSON (dictionary)
damn = Object.keys(damn).map(function(key){
return {date: key, Value: "Total", num: damn[key]};
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment