我有这个脚本:
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 })
}
});
如果脚本被执行,它将起作用。它将显示从第一天到第七天的时间表。 但是,我的问题是数据变量是动态的。因此,一天可能有多个时间表,例如:
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'}
]
也许我应该每天制作一个内部数组(以天为键),这样我可以保存具有多个时间表的数据日。
我该怎么做?
答案 0 :(得分:0)
你能做这样的事吗?
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);
答案 1 :(得分:0)
好的,假设您有这个:
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'}
]
我首先将过滤data
数组以使用您的键获取所有对象,然后将所有这些项目推送到list
结果变量中。一种解决方法是:
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 })
}
});