如何在js中JSON数组按相同元素重新排列成一个新的JSON,求大拿帮助,整了2天了还是没弄好。。

请问大拿们,如何把json1优雅简便的重构成json2呢,具体就是想要把每个menuDate和dinnerTime同时相等的元素分为一组,重构一个json出来。可以使用jquery的。

json1:
[

{
    "menuDate": 1,
    "dinnerTime": "0",
    "num": 5
},
{
    "menuDate": 1,
    "dinnerTime": "0",
    "num": 1
},
{
    "menuDate": 1,
    "dinnerTime": "1",
    "num": 3
},
{
    "menuDate": 2,
    "dinnerTime": "0",
    "num": 3
},
{
    "menuDate": 2,
    "dinnerTime": "0",
    "num": 6
}

]

json2:
[

{
    "menuDate": 1,
    "dinnerTime": "0",
    "value": [
        {
            "menuDate": 1,
            "dinnerTime": "0",
            "num": 5
        },
        {
            "menuDate": 1,
            "dinnerTime": "0",
            "num": 1
        }
    ]
},
{
    "menuDate": 1,
    "dinnerTime": "1",
    "value": [
        {
            "menuDate": 1,
            "dinnerTime": "1",
            "num": 3
        }
    ]
},
{
    "menuDate": 2,
    "dinnerTime": "0",
    "value": [
        {
            "menuDate": 2,
            "dinnerTime": "0",
            "num": 3
        },
        {
            "menuDate": 2,
            "dinnerTime": "0",
            "num": 6
        }
    ]
}

]

阅读 3.5k
评论
    5 个回答
    • 2.6k

    建新对象 jnew={1_2:[],0_1:[]},1_2是 menuDate与dinnerTime的组合,在遍历原json时,根据 menuDate与dinnerTime组合成key,存入jmap,存入时判断一下是新值直接存入,已经有值则将值push入相应数组。遍历完成后,很容易根据jmap生成新json。不知道说明白没,请看代码,result即为所最后结果,在node.js平台测试正确:

    var j1 = [
        {
            "menuDate": 1,
            "dinnerTime": "0",
            "num": 5
        },
        {
            "menuDate": 1,
            "dinnerTime": "0",
            "num": 1
        },
        {
            "menuDate": 1,
            "dinnerTime": "1",
            "num": 3
        },
        {
            "menuDate": 2,
            "dinnerTime": "0",
            "num": 3
        },
        {
            "menuDate": 2,
            "dinnerTime": "0",
            "num": 6
        }
    ]
    var jmap = {};
    var result = [];
    
    j1.forEach(function(al){
        var key = al.menuDate + '_' + al.dinnerTime;
        if(typeof jmap[key] === 'undefined'){
            jmap[key] = [];
        }
        jmap[key].push(al);
    })
    
    var keys = Object.keys(jmap);
    for(var i = 0; i < keys.length; i++){
        var rs = keys[i].split('_');
        result.push({menuDate:rs[0],dinnerTime:rs[1],value:jmap[keys[i]]});
    }