-2

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:

 {"2007": 
      {"label 1": rank, "label 2": rank}, 
 "2008": 
      {"label 1": rank, "label 2": rank}, ...}
Phattwizat
  • 17
  • 2
  • 3
    I might just be tired but I'm having trouble building a relationship between your two samples that makes sense. – Marty Apr 15 '13 at 05:06
  • Can you describe the algorithm somehow (using any paradigm)? It's not clear what you want. – John Dvorak Apr 15 '13 at 05:16
  • To the upvoter: would _you_ please explain _us_ the question? _We_ have no idea what's it asking (I do have an idea, but it's really not clear what the asker wants). – John Dvorak Apr 15 '13 at 05:22
  • @JanDvorak I'm a social scientist new to js so apologies in advance. I've got script that takes the latter nested object as input but the data in the former. Yearly ranks for a given class vs. All classes and ranks in given year. Sorry to lack specificity. – Phattwizat Apr 15 '13 at 05:29

1 Answers1

0

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.

John Dvorak
  • 26,799
  • 13
  • 69
  • 83