简体   繁体   English

如果数据大于1,如何将数据存储在数组中?

[英]How do I store data in an array if the data is more than 1?

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.它将显示从第 1 天到第 7 天的时间表。但是,我的问题是数据变量是动态的。 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.我首先将过滤data数组以使用您的键获取所有对象,然后将所有这些项目推送到list结果变量。 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 })
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM