I’m trying to use reduce to take an array of objects and return an object in below expected format. Able to use it to create object based on validFrom but not able to visulize next steps. Tried to use map as well but didn’t helped much. Help would be really appreciated! Can share stackblitz if helps.
Tried this to simplify but got stuck in next step. First comment
inputArray:
[
{
"day": "Wednesday",
"closeTime": "2000",
"openTime": "0800",
"validFrom": "2001-09-19",
"validTo": "2099-12-31"
},
{
"day": "Tuesday",
"closeTime": "2000",
"openTime": "0800",
"validFrom": "2001-09-19",
"validTo": "2099-12-31"
},
{
"day": "Sunday",
"closeTime": "1630",
"openTime": "0845",
"validFrom": "2001-09-19",
"validTo": "2099-12-31"
},
{
"day": "Thursday",
"closeTime": "2000",
"openTime": "0800",
"validFrom": "2001-09-19",
"validTo": "2099-12-31"
},
{
"day": "Friday",
"closeTime": "2000",
"openTime": "0800",
"validFrom": "2001-09-19",
"validTo": "2099-12-31"
},
{
"day": "Saturday",
"closeTime": "1630",
"openTime": "0845",
"validFrom": "2001-09-19",
"validTo": "2099-12-31"
},
{
"day": "Monday",
"closeTime": "2000",
"openTime": "0800",
"validFrom": "2001-09-19",
"validTo": "2099-12-31"
}
]
Code used:
let clubbedArray = normalData.reduce((acc, temp) => { let { validFrom, day } = temp; return {...acc, [validFrom]: [...(acc[validFrom] || []), day]}; }, {});
Expected Output:
[
{
"day": [
"Friday",
"Wednesday",
"Monday",
"Tuesday",
"Thursday"
],
"closeTime": "2000",
"openTime": "0800",
"validFrom": "2001-09-19",
"validTo": "2099-12-31"
},
{
"day": [
"Saturday",
"Sunday"
],
"closeTime": "1630",
"openTime": "0845",
"validFrom": "2001-09-19",
"validTo": "2099-12-31"
}
]
2
Answers
You can use
Array.prototype.reduce
function to change the shape on an array as you want, Here is the code which allow you to change the shape of your dataPseudocode:
Implementation: