Context: I want to make a timetable planner that checks for time clashes. Any help is greatly appreciated.
Specific Problem: Can't figure out how to split my array of objects into multiple arrays with certain key repeated.
My data set:
let myCourses = [
{
course: "ee3001",
slots: [
{
day: "monday",
time: "0900-1100",
},
{
day: "tuesday",
time: "0930-1100",
},
{
day: "wednesday",
time: "1330-1530",
},
],
},
{
course: "ee3002",
slots: [
{
day: "monday",
time: "0900-1100",
},
{
day: "thursday",
time: "0930-1130",
},
],
},
{
course: "ee3003",
slots: [
{
day: "tuesday",
time: "0930-1100",
},
{
day: "wednesday",
time: "1330-1530",
},
{
day: "thursday",
time: "0930-1130",
},
],
},
];
Arrays I want to split it into:
let newarray = [
{
course: "ee3001",
slot: {
day: "monday",
time: "0900-1100",
},
},
{
course: "ee3001",
slot: {
day: "monday",
time: "1300-1400",
},
},
...
...
];
let newArray2 = //containing info on ee3002
let newArray3 = //containing info on ee3003
**Note:**Dataset is to be populated, ie. users are able to add more courses and timings.
Here I am using map to iterate through your array and inside that iteration I am again using map to iterate through the slots.
let myCourses = [
{
course: "ee3001",
slots: [
{
day: "monday",
time: "0900-1100",
},
{
day: "tuesday",
time: "0930-1100",
},
{
day: "wednesday",
time: "1330-1530",
},
],
},
{
course: "ee3002",
slots: [
{
day: "monday",
time: "0900-1100",
},
{
day: "thursday",
time: "0930-1130",
},
],
},
{
course: "ee3003",
slots: [
{
day: "tuesday",
time: "0930-1100",
},
{
day: "wednesday",
time: "1330-1530",
},
{
day: "thursday",
time: "0930-1130",
},
],
},
];
const newArray=[]
myCourses.forEach(myFunction);
function myFunction(item, index) {
newArray[index] = [];
item.slots.map((child) =>
newArray[index].push({ course: item.course, slots: child })
);
}