[Solved] Reordering array of objects into nested objects [closed]

[ad_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 key Class
    • make year a key in output, mapping to the object:
      • each key in output[year] is the value class of Class in some row, mapping to the value:
        • output[year][class] = input.find("Class",class)[year]

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.

[ad_2]

solved Reordering array of objects into nested objects [closed]