JSFiddle - React, Tailwind, and code Playground
by A B Jones
JavaScript
var data = [{ //data set converted to JSON for easier use
"org": "GSK",
"org_cat": "industry",
"2004_passed": 35,
"2004_total": 100,
"2005_passed": 45,
"2005_total": 100,
"2006_passed": 55,
"2006_total": 100
}];
var newData = {}; //new data container
for (var i = 0; i < data.length; i++) { //loop through data array (this is so you can use this on a bigger sized array)
var thisObj = {}; //create empty object
thisObj.org_cat = data[i].org_cat; //set org_cat
thisObj.data = []; //set data to empty array to populate later
for (var key in data[i]) { //loop through data[i]
if (key != 'org' && key != 'org_cat') { //check this key is not org or org_cat
var thisData = {}; //create empty data object
var thisYear = key.toString().substring(0, 4); //get year by using substring
thisData.year = thisYear; //set year
thisData.passed = data[i][thisYear + '_passed']; //set passed at this year
thisData.total = data[i][thisYear + '_total']; //set total at this year
thisObj.data.push(thisData); //push this data to data array
}
}
var uniqueDates = []; //set empty array to use to remove duplicate items in data array
for (var j = 0; j < thisObj.data.length; j++) { //loop through data array created earlier
if (uniqueDates.indexOf(thisObj.data[j].year) < 0) { //if this year doesn't exist in unique array above, push it in
uniqueDates.push(thisObj.data[j].year); //push it in
} else {
thisObj.data.splice(j--, 1); //remove duplicate data
}
}
newData[data[i].org] = thisObj; //set data @ current org to be object created above
}
console.log('newData', newData) //log new data