JSON Group by count,输出到键值对json结果

时间:2016-03-13 19:50:19

标签: javascript json underscore.js

我有以下JSON数据

"rows": [{  
        "createdDate": "3/11/2016",
        "createdBy": "Bob"          
    },{ 
        "createdDate": "3/12/2016",
        "createdBy": "Megan"            
    },{ 
        "createdDate": "3/12/2016",
        "createdBy": "Bob"          
    },{ 
        "createdDate": "3/13/2016",
        "createdBy": "Sam"          
    },{ 
        "createdDate": "3/11/2016",
        "createdBy": "Bob"          
    },]

我想要输出图表,我可以按任何属性名称进行分组,例如在'createdBy'上:

"result": [{
        "key": "Bob",
        "value": 3,         
    },{
        "key": "Megan",
        "value": 1,         
    },{
        "key": "Sam",
        "value": 1,         
    },

我有JSON,需要在绑定到我的图表之前以下列格式操作它。我从下划线尝试了_groupBy,但无法得到理想的结果。

2 个答案:

答案 0 :(得分:6)

减少行数以createBy属性计算每个对象的出现次数。 occurences将是一个对象,其中的键是名称(如Bob1Megan,...),值是出现次数。然后使用Object.keys()遍历此对象并将其映射到结果:

var rows = [
    { 'createdDate': '3/11/2016', 'createdBy': 'Bob' },
    { 'createdDate': '3/12/2016', 'createdBy': 'Megan' },
    { 'createdDate': '3/12/2016', 'createdBy': 'Bob' },
    { 'createdDate': '3/13/2016', 'createdBy': 'Sam' },
    { 'createdDate': '3/11/2016', 'createdBy': 'Bob' },
];

var occurences = rows.reduce(function (r, row) {
    r[row.createdBy] = ++r[row.createdBy] || 1;
    return r;
}, {});

var result = Object.keys(occurences).map(function (key) {
    return { key: key, value: occurences[key] };
});

console.log(result);

答案 1 :(得分:1)

只有一个循环的解决方案。



var rows = [{ createdDate: "3/11/2016", createdBy: "Bob" }, { createdDate: "3/12/2016", createdBy: "Megan" }, { createdDate: "3/12/2016", createdBy: "Bob" }, { createdDate: "3/13/2016", createdBy: "Sam" }, { createdDate: "3/11/2016", createdBy: "Bob" }],
    group = function (array) {
        var r = [], o = {};
        array.forEach(function (a) {
            if (!o[a.createdBy]) {
                o[a.createdBy] = { key: a.createdBy, value: 0 };
                r.push(o[a.createdBy]);
            }
            o[a.createdBy].value++;
        });
        return r;
    }(rows);

document.write('<pre>' + JSON.stringify(group, 0, 4) + '</pre>');
&#13;
&#13;
&#13;