基于日期对汇总JSONObject条目

时间:2015-11-30 17:18:30

标签: jquery arrays json

我有一个包含一些JSON对象的数组,如下所示:

[{
    "date": "2015-10-02",
    "in": 79,
    "out": 78,
    "total": 157
}, {
    "date": "2015-10-05",
    "in": 80,
    "out": 55,
    "total": 135
}, {
    "date": "2015-10-02",
    "in": 70,
    "out": 61,
    "total": 131
}, {
    "date": "2015-10-05",
    "in": 0,
    "out": 125,
    "total": 125
}, {
...
}]

我想总结一下" in / out / total"基于日期值的值。在此示例中,预期结果为:

   [{
        "date": "2015-10-02",
        "in": 149,
        "out": 139,
        "total": 288
    }, {
        "date": "2015-10-05",
        "in": 80,
        "out": 180,
        "total": 260
    }]

我怎么能用jQuery做到这一点?

1 个答案:

答案 0 :(得分:1)

我已创建此功能

function sumJson(json, key){

    // Create a blank object
    var check = {};

    // Parse through the json
    [].forEach.call(json, function(x){
        var d = x.date;
        // Check if date exist as a key in the object check
        if(check.hasOwnProperty(d)){
            // If yes increase the values accordingly
            check[d].in += x.in;
            check[d].out += x.out;
            check[d].total += x.total;
        }
        else{
            // Else create a same object
            check[d] = x;
        }
    });
    var ret = [];
    // Bring the check json in format
    [].forEach.call( Object.keys(check), function(inst){
        ret.push(check[inst]);
    });
    // return the formatted array
    return ret;
}

// First param is the json and second one is the key on which the data is to be grouped
console.log(sumJson(x, "date"));

Live fiddle