1. 程式人生 > >js把json中相同key的資料重新組成一個新的json

js把json中相同key的資料重新組成一個新的json

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]]}); }