Javascript:重组JSON

时间:2014-02-19 14:51:32

标签: javascript jquery json

我需要使用Javascript / Jquery将我的JSON重组为新结构,但我不知道如何做到这一点。

我当前的JSON看起来像,

{
   'dishList': [
  {
   'dishName': 'bla-bla1',
   'dishNumber': 4,
    'dishType': 'Type 1'
  },
   {
   'dishName': 'bla-bla2',
   'dishNumber': 12,
   'dishType': 'Type 1'
  },
  {
   'dishName': 'bla-bla3',
   'dishNumber': 2,
   'dishType': 'Type 2'
  }
 ]
}

我需要以下结构:

{
'dishList': [
    {
    'dishType': 'Type 1',
    'dishes': [
        {
         'dishName': 'bla-bla1',
         'dishNumber': 4
        },
        {
         'dishName': 'bla-bla2',
         'dishNumber': 12
        }
    ]
    },
    {
    'dishType': 'Type 2',
    'dishes': [
        {
         'dishName': 'bla-bla3',
         'dishNumber': 2
        }
        ]
    }
]
}

任何想法我该怎么做?

谢谢。

3 个答案:

答案 0 :(得分:4)

以下代码将针对此特定情况对其进行重组。我确信有一种更有效的方法可以做到这一点,也可能是一种更抽象的方式:

var orig_json = {
        "dishList": [{
            "dishName": "bla-bla1",
                "dishNumber": 4,
                "dishType": "Type 1"
        }, {
            "dishName": "bla-bla2",
                "dishNumber": 12,
                "dishType": "Type 1"
        }, {
            "dishName": "bla-bla3",
                "dishNumber": 2,
                "dishType": "Type 2"
        }]
    },
    new_json;
var reorg = function (data) {
    var types = [],
        dishes = [];
    // pass 1, add distinct types
    data.dishList.forEach(function (value, index, array) {
        if (types.indexOf(value.dishType) === -1) {
            // doesn't yet exist
            types.push(value.dishType);
        }
    });
    // for each distinct type
    types.forEach(function (value, index, array) {
        // pass two to n, reorganize based on type
        data.dishList.forEach(function (val, i, a) {
            if (val.dishType === value) {
                // matches dishType
                dishes.push({
                    "dishName": val.dishName,
                    "dishNumber": val.dishNumber
                });
            }
        });
        // redefine value of current array element
        array[index] = {
            "dishType": value,
            "dishes": dishes
        };
        // reset dishes array
        dishes = [];
    });
    return {
        "dishList": types
    };
};
new_json = reorg(orig_json);

这是一个小提琴:http://jsfiddle.net/NYhBM/

答案 1 :(得分:2)

尝试此功能:

var f = function(json){
    var obj = {};

    // put dishes into a temporary object
    // that has properties named as dish types
    // and its values are array of dish objects of that type
    for(var i=0;i<json.dishList.length;i++){
        if(!obj[json.dishList[i].dishType])
                obj[json.dishList[i].dishType] = [];
        obj[json.dishList[i].dishType].push({
            dishName: json.dishList[i].dishName,
            dishNumber: json.dishList[i].dishNumber,
        })
    }   
    var res = {
        dishList: []
    }

    // loop through properties of obj i.e. dish types
    // and populate the ouptput dishlist.
    for(var p in obj){
        if(obj.hasOwnProperty(p))
            res.dishList.push({
                dishType: p,
                dishes: obj[p]
            });
    }
    return res;
}

用你的输入json调用它,它将返回输出。

答案 2 :(得分:0)

你必须为此做一个 ad-hoc 函数/循环 这有点你需要做的事情:

// if you return a value in the function below, do this:
yourJson.dishList = reorganizeDishList(yourJson);

function reorganizeDishList(yourJson) {
    var dishList = yourJson.dishList;
    var tmpJson = {}; // this json will hold {type:[array of properties]}
    for (var i in dishList) { // loop ALL the dishes
        var properties = {}; // will hold all properties but type
        var type = '';
        for (var j in dishList[i]) { // loop All the properties of the dish
            if (j == 'dishType') {
                type = dishList[i][j];
            } else {
                properties[j] = dishList[i][j];
            }
        }
        if (!tmpJson[type]) {
            tmpJson[type] = []; // create array if tmpJson[type] is undefined
        }
        tmpJson[type].push(properties);
    }
    dishList = []; // clear old dishList
    for (var i in tmpJson) {
        // create newly organized array ("list")
        dishList.push({dishType: i, dishes: tmpJson[i]});
    }
    return dishList;
    // or `yourJson.dishList = dishList` instead of returning a value
}