将对象数组重新排序为嵌套对象 [英] Reordering array of objects into nested objects

查看:70
本文介绍了将对象数组重新排序为嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重新排列对象数组

[ {"2007": rank, "2008": rank, "Class": "label 1"}, 
  {"2007": rank, "2008": rank, "Class": "label 2"}, ... ]

放入嵌套对象,例如:

 {"2007": 
      {"label 1": rank, "label 2": rank}, 
 "2008": 
      {"label 1": rank, "label 2": rank}, ...}


推荐答案

要求是按 Class 来转置表和索引:

It seems that your requirement is to transpose the table and index by Class:


  • 调用输入表格

  • 调用数组行中的每个元素

  • 是至少一行中的键,除了键 Class

    • make year 输出中的键,映射到对象:

      • output [year] 是某行中 Class 的值 class v提示:

        • output [year] [class] = input.find( Class ,class)[year]

        • 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;
              

              测试: http://jsfiddle.net/aT5YG/1

              如果多个行具有相同的 Class ,后面的行将覆盖前面的行。如果nput呈锯齿状,则输出将呈锯齿状。

              If multiple rows have the same Class, the later rows overwrite the previous rows. If the nput was jagged, the output will be jagged.

              这篇关于将对象数组重新排序为嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆