group array data by json properties js code example
Example 1: javascript group by property array of objects
function groupArrayOfObjects(list, key) {
return list.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
var people = [
{sex:"Male", name:"Jeff"},
{sex:"Female", name:"Megan"},
{sex:"Male", name:"Taylor"},
{sex:"Female", name:"Madison"}
];
var groupedPeople=groupArrayOfObjects(people,"sex");
console.log(groupedPeople.Male);
console.log(groupedPeople.Female);
Example 2: js json groupby prop
var myJsonFromSQL = [{id:1, cat:'test1'},{id:2, cat:'test1'},
{id:3, cat:'test2'},{id:4, cat:'test2'}];
const arr_cat = [...new Set(myJsonFromSQL.map(i => i.cat))];
You will get an array with the property values grouped:
arr_cat ['test1','test2']