I have below array of JSON. I want to set schedules for the dayOfWeek
which are not present inside the schedules
of the other rooms
const data = {
rooms: [
{
roomId: 1,
schedules: []
},
{
roomId: 2,
schedules: [
{ home1: "05:05", dayOfWeek: 1, away: "20:30" },
{ home1: "06:05", dayOfWeek: 5, away: "21:30" },
{ home1: "07:05", dayOfWeek: 7, away: "22:30" }
]
},
{
roomId: 3,
schedules: []
}
]
}
I need to copy the same schedules to the other rooms as well.
expected output
const finalArray = [
{ home1: "05:05", dayOfWeek: 1, away: "20:30", roomId: 1 }, //schedules from room2
{ home1: "06:05", dayOfWeek: 5, away: "21:30", roomId: 1 }, //schedules from room2
{ home1: "07:05", dayOfWeek: 7, away: "22:30", roomId: 1 }, //schedules from room2
{ home1: "05:05", dayOfWeek: 1, away: "20:30", roomId: 3 }, //schedules from room2
{ home1: "06:05", dayOfWeek: 5, away: "21:30", roomId: 3 }, //schedules from room2
{ home1: "07:05", dayOfWeek: 7, away: "22:30", roomId: 3 }, //schedules from room2
]
I have tried but could not get it work!!! Please help!!!
You can first find the source of truth room
and then use Array.reduce
to extract/copy the schedules to the others:
const data = { rooms: [ { roomId: 1, schedules: [] }, { roomId: 2, schedules: [ { home1: "05:05", dayOfWeek: 1, away: "20:30" }, { home1: "06:05", dayOfWeek: 5, away: "21:30" }, { home1: "07:05", dayOfWeek: 7, away: "22:30" } ] }, { roomId: 3, schedules: [] } ] }
const theRoom = data.rooms.find(x => x.schedules.length)
const result = data.rooms.reduce((r,{roomId, schedules}) => {
if(roomId != theRoom.roomId)
r.push(...theRoom.schedules.map(x => ({ roomId, ...x })))
return r
}, [])
console.log(result)