Issue
inputs array:
weekSchedules: [
{
dayId: 1,
daySchedules: [
{
batchScheduleId: 1,
Time: 12:00
},
{
batchScheduleId: 1,
ime: 12:30
},
{
batchScheduleId: 2,
Time: 13:00
},
{
batchScheduleId: 2,
Time: 13:30
}
]
},
{
dayId: 2,
daySchedules: [
{
batchScheduleId: 1,
Time: 12:00
},
{
batchScheduleId: 1,
Time: 12:30
},
{
batchScheduleId: 2,
Time: 13:00
},
{
batchScheduleId: 2,
Time: 13:30
}
]
}
}
]
output array:
[
{
batchScheduleId: 1,
Time:[12:00,12.30],
dayId: [1,2]
},
{
batchScheduleId: 2,
Time:[12:00,12.30],
dayId: [1,2]
}
]
i need transform input array objects to output array objects given below in angular typescript. i tried using plain JavaScript but for that i have to write lots of code so i want simplify code to achieve this.
to acheive this i have to write multiple for loops and if condition but i want to avoid it and the solution should more generic so that i can use the same solution in multiple places just by changing the key. it would be better if the solution uses loadsh for this requirement and plain JavaScript approach is not required.
Solution
You can try to use reduce function to avoid using the if and the for
const inputObject = {weekSchedules:[{dayId:1,daySchedules:[{batchScheduleId:1,Time:"12: 00"},{batchScheduleId:1,Time:"12: 30"},{batchScheduleId:2,Time:"13: 00"},{batchScheduleId:2,Time:"13: 30"}]},{dayId:2,daySchedules:[{batchScheduleId:1,Time:"12: 00"},{batchScheduleId:1,Time:"12: 30"},{batchScheduleId:2,Time:"13: 00"},{batchScheduleId:2,Time:"13: 30"}]}]}
const flattenedBatch = inputObject.weekSchedules
.reduce((prev, next) => [
...prev, ...next.daySchedules.map(({batchScheduleId, Time}) => ({batchScheduleId, dayId: next.dayId, Time}))
], [])
const groupedData = flattenedBatch.reduce((prev, next) => {
const prevValue = prev?.[next.batchScheduleId] ? prev[next.batchScheduleId].dayId : [];
prevValue.push(next.dayId)
const prevTime = prev?.[next.batchScheduleId] ? prev[next.batchScheduleId].Time : [];
prevTime.push(next.Time)
return {...prev, [next.batchScheduleId]: {
batchScheduleId: next.batchScheduleId,
dayId: [...new Set(prevValue)],
Time: [...new Set(prevTime)]
}}
}, {});
const outputData = Object.values(groupedData)
console.log(outputData)
Answered By - Owen Kelvin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.