I am faced with a JSON query that contains the Date, Value, Country, and Number fields. My goal is to create two separate JSON dictionaries based on unique dates (there will be two of them). The desired output can be seen in the code snippet below along with my attempts.
var json_data = {"headers":["Time","Value","Country","Number"],"rows":[["2018-09-01","#value1","United Kingdom",25],
["2018-10-01","#value1","United Kingdom",15],
["2018-09-01","#value2","United Kingdom",10],
["2018-10-01","#value2","United Kingdom",65],
["2018-09-01","#value3","United Kingdom",60],
["2018-10-01","#value3","United Kingdom",40],
["2018-09-01","#value1","Germany",55],
["2018-10-01","#value1","Germany",85],
["2018-09-01","#value2","Germany",90],
["2018-10-01","#value2","Germany",30],
["2018-09-01","#value3","Germany",20],
["2018-10-01","#value3","Germany",25],
["2018-09-01","#value1","France",55],
["2018-10-01","#value1","France",40],
["2018-09-01","#value2","France",90],
["2018-10-01","#value2","France",75],
["2018-09-01","#value3","France",30],
["2018-10-01","#value3","France",80]]};
var dataRows = json_data.rows;
var dateFields = ["2018-10-01", "2018-09-01"];
var dateMap = {};
dataRows.forEach(function(d) {
var date = d[0];
dateMap[date] = [];
dateFields.forEach(function(field) {
var object = {"data":[{"yValue": d[1], "xValue": +d[3]}]};
dateMap[date].push( object );
});
});
document.getElementById("yellow").innerHTML =JSON.stringify(dateMap["2018-09-01"]);
///Target data example
var target = [{
data: [{
yValue: '#value1',
xValue: 25
}, {
yValue: '#value2',
xValue: 10
}, {
yValue: '#value3',
xValue: 60
}],
name: 'United Kingdom'
}, {
data: [{
yValue: '#value1',
xValue: 55
}, {
yValue: '#value2',
xValue: 90
}, {
yValue: '#value3',
xValue: 20
}],
name: 'France'
},{
data: [{
yValue: '#value1',
xValue: 55
}, {
yValue: '#value2',
xValue: 90
}, {
yValue: '#value3',
xValue: 20
}],
name: 'Germany'
}
];
document.getElementById("purple").innerHTML =JSON.stringify(target);
///A group by attempt
//Create dictionary function (transformed JSON)
createDict = (data) => {
let groups = data.reduce((acc, arr) => {
if (acc.hasOwnProperty(arr[1])) {
acc[arr[1]].push(arr);
} else {
acc[arr[1]] = [arr];
}
return acc;
}, {});
let results = [];
let final = [];
for (let g in groups) {
let obj = {yValue: g};
let a = groups[g][0];
let b = groups[g][1];
let c = groups[g][2];
obj.xValue = a[3];
results.push(obj);
}
final.push(results,"name");
return results;
}
var grouped = createDict(dataRows);
document.getElementById("red").innerHTML =JSON.stringify(grouped);
<h4>Data of first branch (First date)</h4>
<div style="background:yellow;" id="yellow"></div>
<h4>Target Data (How I want it to look like)</h4>
<div style="background:green; color:white" id="purple"></div>
<h4>A group by attempt</h4>
<div style="background:red; color:white" id="red"></div>