I have this array of objects, that I need to modify to make the rendering easier . I used some code mentioned in a similar question : Group array of object nesting some of the keys with specific names
Here's my array and code
function groupAndMap(events, Year, Month, predic){
return _.map(_.groupBy(events,Year), (obj,key) => ({
[Year]: key,
[Month]: (predic && predic(obj)) || obj
}));
}
const items = [
{
"Year": 2018,
"Month": 7,
"Day": 2,
"Title": "event1",
"StartDate": "2018-07-02T10:00:00.000Z",
"EndDate": "2018-07-02T11:00:00.000Z"
}, {
"Year": 2018,
"Month": 8,
"Day": 31,
"Title": "event2",
"StartDate": "2018-07-31T10:00:00.000Z",
"EndDate": "2018-08-02T11:00:00.000Z"
}
];
function groupAndMap(items, itemKey, childKey, predic){
return _.map(_.groupBy(items,itemKey), (obj,key) => ({
[itemKey]: key,
[childKey]: (predic && predic(obj)) || obj
}));
}
var result = groupAndMap(items,"Year","Months",
arr => groupAndMap(arr,"Month", "Days"));
var jsonvalue = JSON.stringify(result);
document.write(jsonvalue);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
I want my output to be in the following format
[{
"Year": "2019",
"Months": [{
"Month": "8",
"Days": [{
"Day": "31",
"Events": [{
"Year": 2019,
"Month": 8,
"Day": 31,
"Title": "event3",
"StartDate": "2018-07-31T10:00:00.000Z",
"EndDate": "2018-08-02T11:00:00.000Z"
}]
}]
}]
}]
How should i modify the code in order to get this result ?