Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Group by count, output to key value pair json result

I have following JSON data

"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"          
    },]

And I want output for charting where I can group by any property name for count, for example here on 'createdBy' :

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

I have the JSON and need to manipulate it in following format before binding to my chart. I tried _groupBy from underscore but could not get desired result.

like image 399
Gaurav Avatar asked Dec 10 '22 17:12

Gaurav


2 Answers

Reduce rows to count occurences of each object by createBy property. occurences will be an object which keys are names (like Bob1, Megan, ...) and values are count of occurences. Then use Object.keys() to loop through this object and map it to the result:

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);
like image 141
madox2 Avatar answered Dec 26 '22 17:12

madox2


A solution with only one loop.

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>');
like image 29
Nina Scholz Avatar answered Dec 26 '22 19:12

Nina Scholz