It seems that your requirement is to transpose the table and index by Class:
- call the input “table”
- call every element of the array “row”
- for every
yearthat is a key in at least one row, except the keyClass- make
yeara key inoutput, mapping to the object:- each key in
output[year]is the valueclassofClassin some row, mapping to the value:output[year][class]=input.find("Class",class)[year]
- each key in
- make
This is one possible implementation:
var input = [ {"2007": rank, "2008": rank, "Class": "label 1"},
{"2007": rank, "2008": rank, "Class": "label 2"} ]
//////////
var yr, i;
var output = {};
for(i=0; i<input.length; i++){
var row = input[i];
for(yr in row){
output[yr] = output[yr] || {};
output[yr][row.Class] = row[yr];
}
}
//////////////
return output;
test: http://jsfiddle.net/aT5YG/1
If multiple rows have the same Class, the later rows overwrite the previous rows. If the nput was jagged, the output will be jagged.
solved Reordering array of objects into nested objects [closed]