I have this script:
let data = [
{day: 1, time: '08:00', note: 'madrid'},
{day: 2, time: '08:00', note: 'barcelona'},
{day: 3, time: '10:00', note: 'juventus'},
]
let days = [7, 1, 2, 3, 4, 5, 6]
let list = []
days.forEach(element => {
let item = data.find(x => x.day === element)
if (item) {
list.push(item)
} else {
list.push({ day: element, time: undefined })
}
});
If the script is executed, it works. It will show schedule from day 1 to day 7. However, my problem is that the data variable is dynamic. So one day may have more than one schedule, like here:
let data = [
{day: 1, time: '08:00', note: 'madrid'}, {day: 1, time: '09:00', note: 'chelsea'},
{day: 2, time: '08:00', note: 'barcelona'}, {day: 2, time: '09:00', note: 'mu'},
{day: 3, time: '10:00', note: 'juventus'}
]
Maybe I should make an inner array per day (day as the key), so I can save data days that have more than one schedule.
How do I do that?
Would you be able to do something like this?
let data = [
{day: 1, time: '08:00', note: 'madrid'}, {day: 1, time: '09:00', note: 'chelsea'},
{day: 2, time: '08:00', note: 'barcelona'}, {day: 2, time: '09:00', note: 'mu'},
{day: 3, time: '10:00', note: 'juventus'}
]
let days = [7, 1, 2, 3, 4, 5, 6];
let list = [];
days.forEach(day => {
list.push({day, schedule: [...data.filter(d => d.day === day)]
.map(d => ({time: d.time, note: d.note}))
})
});
console.log(list);
Okay, let's say you have this:
let days = [7, 1, 2, 3, 4, 5, 6]
let data = [
{day: 1, time: '08:00', note: 'madrid'},
{day: 1, time: '09:00', note: 'chelsea'},
{day: 2, time: '08:00', note: 'barcelona'},
{day: 2, time: '09:00', note: 'mu'},
{day: 3, time: '10:00', note: 'juventus'}
]
I first would filter the data
array to obtain all objects with your key, and then I would push all those items to the list
result variable. One approach for that could be:
days.forEach( d => {
let daySchedule = data.filter(elem => {
elem.day === d;
});
if (daySchedule.length > 0) {
daySchedule.forEach( elem => list.push(elem) );
}
else {
list.push({ day: d, time: undefined })
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.