Reordering Array Of Objects Into Nested Objects
How do I reorder an array of objects [ {'2007': rank, '2008': rank, 'Class': 'label 1'}, {'2007': rank, '2008': rank, 'Class': 'label 2'}, ... ] into a nested object such as:
Solution 1:
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
year
that is a key in at least one row, except the keyClass
- make
year
a key inoutput
, mapping to the object:- each key in
output[year]
is the valueclass
ofClass
in 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.
Post a Comment for "Reordering Array Of Objects Into Nested Objects"