There is a function that groups an array of objects by key. For example an array:
data: [
{
CS_NAME: "AAA",
IS_MAIN: "Y",
WEBSITE_CREATE_DATE: "2021-06-01T15:50:37.687",
},
{
CS_NAME: "AAA",
IS_MAIN: "N",
WEBSITE_CREATE_DATE: "2021-08-03T12:02:58.07",
},
{
CS_NAME: "BBB",
IS_MAIN: "Y",
WEBSITE_CREATE_DATE: "2021-08-03T12:02:58.07",
},
{
CS_NAME: "BBB",
IS_MAIN: "N",
WEBSITE_CREATE_DATE: "2019-01-26T00:00:00",
},
{
CS_NAME: "CCC",
IS_MAIN: "Y",
WEBSITE_CREATE_DATE: "2019-01-26T00:00:00",
},
]
Function groupBy:
groupBy(input, key) {
return input.reduce((acc, currentValue) => {
let groupKey = currentValue[key];
if (!acc[groupKey]) {
acc[groupKey] = [];
}
acc[groupKey].push(currentValue);
return acc;
}, {});
},
let obj = groupBy(data, "CS_NAME");
How to change this function so that it returns an array of objects, each of which will have two fields:
{
title: "CS_NAME" // the key by which objects were grouped or any other property
content: {obj} // the whole object
}
For example, the output should be like this:
{
title: "AAA",
content: [
{
CS_NAME: "AAA",
IS_MAIN: "Y",
WEBSITE_CREATE_DATE: "2021-06-01T15:50:37.687",
},
{
CS_NAME: "AAA",
IS_MAIN: "N",
WEBSITE_CREATE_DATE: "2021-08-03T12:02:58.07",
},
],
}