jquery - 一个扁平的json字符串到一个分组的嵌套jquery字符串

时间:2015-01-09 04:02:40

标签: jquery json nested

我有一个扁平的json文件

[{"Category":"WO","cfg_item":"WO10018","ID":43,"SortOrder":43},
{"Category":"Milestone Status","cfg_item":"Open","ID":23,"SortOrder":1},
{"Category":"Milestone Status","cfg_item":"Complete","ID":24,"SortOrder":2},
{"Category":"Milestone Status","cfg_item":"Ready","ID":218,"SortOrder":0},
{"Category":"Milestone Health","cfg_item":"Green","ID":14752,"SortOrder":0},
{"Category":"Milestone Health","cfg_item":"Amber","ID":14753,"SortOrder":1}]

我想使用jquery对这个文件进行分组和嵌套。

[
   {
      "Category":"Milestone Health",
      "data":[
         {
            "ID":14752,
            "cfg_item":"Green",
            "SortOrder":0
         },
         {
            "ID":14753,
            "cfg_item":"Amber",
            "SortOrder":1
         }
      ]
   },
   {
      "Category":"Milestone Status",
      "data":[
         {
            "ID":218,
            "cfg_item":"Ready",
            "SortOrder":0
         },
         {
            "ID":23,
            "cfg_item":"Open",
            "SortOrder":1
         },
         {
            "ID":24,
            "cfg_item":"Complete",
            "SortOrder":2
         }
      ]
   }
]

请在这里找到一个jsfiddle http://jsfiddle.net/2bitcoder/5dsygone/

到目前为止,我已嵌套但未对数据进行分组 - 我不确定如何进行分组。

var newjson = jsondata.map(function (item) {
        var obj = {};
        obj[item.Category] = { cfg_item: item.cfg_item, ID: item.ID, SortOrder: item.SortOrder};
        return obj;
    });

2 个答案:

答案 0 :(得分:0)

如果你不介意使用underscore.js,这里有一个简单的方法:

_.map(_.groupBy(collection, "Category"), function(value, key) {
  return {
    "Category": key,
    "data": value
  }
});

Demo with ommiting the category in the "data" property

答案 1 :(得分:0)

可以通过构建一个临时对象来实现它,该对象的键是类别,然后遍历该对象以构建最终数组

var tmp = {}, newjson = [];

$.each(jsondata, function(_, item){
    if(!tmp[item.Category] ){
        tmp[item.Category] = [];
    }        
    tmp[item.Category].push( item);  
    delete item.Category;  
});

$.each( tmp, function( category, dataArr){        
    newjson.push({Category: category, data: dataArr})
});

DEMO