I have a JSON data and I need to do something like group by and i asked this question before here but i am not getting any satisfied answer so this time i would like to expl
Use first class functions to create generic group by key reducers and a sorters. I will take the reducer from a previous answer of mine. That way you can sort and group by any key you like, in a similar way that you would do in SQL.
const groupBy = key => (result,current) => {
const item = Object.assign({},current);
if (typeof result[current[key]] == 'undefined'){
result[current[key]] = [item];
}else{
result[current[key]].push(item);
}
return result;
};
const stringSortBy = key => (a,b) => {
const sa = a[key];
const sb = b[key];
return sa < sb ? -1 : +(sa > sb);
};
const myObject = {
"Apps": [
{
"Name": "app1",
"id": "1",
"groups": [
{
"id": "1",
"name": "test group 1",
"category": "clinical note",
"author": "RRP"
}, {
"id": "2",
"name": "test group 2",
"category": "clinical image",
"author": "LKP"
}, {
"id": "3",
"name": "test group 3",
"category": "clinical document",
"author": "RRP"
}, {
"id": "4",
"name": "test group 4",
"category": "clinical note",
"author": "John"
}
]
}
]
}
const categories = myObject.Apps[0].groups.reduce(groupBy('category'),{});
console.log(categories);
const sorted = myObject.Apps[0].groups.sort(stringSortBy('author'));
console.log(sorted);