Last active
December 16, 2018 11:41
-
-
Save ApoloSiskos/23d3aa7e0090aa7db6b0c8fe45211938 to your computer and use it in GitHub Desktop.
Datorama JSON - Group by number (variable) of dimensions (objects) and convert to a dictionary (array of objects) in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Group JSON string by a number of dimensions (number is a variable) and convert to a dictionary (array of objects) in Javascript | |
<div style="background:yellow; "id="original"></div> | |
<div style="background:red;" id="output"></div> | |
<script> | |
var json_data = {"headers":["Month","Value","Number"],"rows":[["2018-10-01 00:00:00.0","one",209],["2018-10-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-09-01 00:00:00.0","four",192]]}; | |
//const json_data = {Query.JSON}; | |
//Group by function | |
function groupBy(rows, numObjects) { | |
const | |
rowMap = new Map(), | |
result = [], | |
dataTemp = []; | |
// Iterate over the rows. | |
rows.forEach(row => { | |
// Create a key, it is the first elements joined together. | |
const key = row.slice(0,numObjects).join(); | |
// Check if the Map has the generated key... | |
if (rowMap.has(key)) { | |
// The map has the key, we need to add up the values | |
// Get the value for the current key. | |
const storedRow = rowMap.get(key); | |
// Add the value of the current row to the row in the map. | |
storedRow[2] += row[2]; | |
} else { | |
// The key doens't exist yet, add the row to the map. | |
rowMap.set(key, row); | |
} | |
}); | |
// Iterate over all the entries in the map and push each value with the summed up value into the array. | |
rowMap.forEach(value => { | |
result.push(value); | |
}); | |
for (i = 0; i < result.length; i++) | |
{ | |
var object = {"date": result[i][0].slice(0,10), "Value": result[i][1], "num": result[i][2]}; | |
dataTemp.push(object); | |
} | |
return dataTemp; | |
} | |
data = groupBy(json_data.rows,2); | |
document.getElementById("output").innerHTML =JSON.stringify(data); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment