I have an API call which returns data in such format:
const testScheduleData = [
{
DATE: "2021-06-20",
SELECTED: false,
STARTINGDAY: true,
ENDINGDAY: true,
STATUS: "WORK",
COLOR: "green",
},
{
DATE: "2021-06-21",
SELECTED: false,
STARTINGDAY: true,
ENDINGDAY: true,
STATUS: "HALFDAY",
COLOR: "green",
},
];
I need to restructure it to an object of objects in such format:
Object {
"2021-06-20": Object {
"color": "green",
"endingDay": true,
"selected": false,
"startingDay": true,
},
"2021-06-21": Object {
"color": "green",
"endingDay": true,
"selected": false,
"startingDay": true,
},
the way I do it is first to map the testScheduleData to array (ignore item.STATUS for now):
const datesArr = testScheduleData.map((item, index) => ({
[item.DATE]: {
startingDay: item.STARTINGDAY,
endingDay: item.ENDINGDAY,
color: item.COLOR,
selected: item.SELECTED,
},
}));
and then use reduce to create an object from it:
var datesObj = datesArr(function (result, item) {
var key = Object.keys(item)[0];
result[key] = item[key];
return result;
}, {});
which returns the correct result, but seems like an overdo. Is there a way to simplify those two steps?
const datesArr = Object.assign({}, ...datesArr). But probably you should just do the mapping inside thereducecallbackObject.fromEntries(testScheduleData.map(item => { let {DATE, ...rest} = item; return [DATE, rest]; }))