我尝试循环遍历一个数组作为其中一个参数的数组失败,我需要遍历该嵌套数组以便根据规范进行映射,然后我需要在父循环完成后运行一个函数。有人能指出我完成这个错误的错误吗?
const schedule = {}
data.schedule.forEach(item => {
let date = moment(item.date).format('YYYY-MM-DD')
let eventList = []
item.events.forEach(event => {
let start = moment(event.start).format('h:mm A')
let end = moment(event.end).format('h:mm A')
let time = `${start} - ${end}`
eventList.push({time: time, name: event.name})
})
return Promise.all(eventList).then(list => {
console.log('list', list)
schedule[`${date}`] = list
})
})
// this is my issue:
Promise.all(schedule).then(list => {
console.log('schedule:', list)
})
// which bombs the method with:
// TypeError: (var)[Symbol.iterator] is not a function
// at Function.all (native)
我实际上需要返回一个类似于此的对象:
{'2017-12-06': [
{time: '9am - 10am', name: 'Jackson Home'},
{time: '11AM - 3PM', name: 'Jackson Home'},
{time: '3PM - 8PM', name: 'Jackson Home'}
]}
答案 0 :(得分:0)
const schedule = {}
data.schedule.forEach(item => {
let date = moment(item.date).format('YYYY-MM-DD')
let eventList = []
schedule[`${date}`] = item.events.map(event => {
let start = moment(event.start).format('h:mm A')
let end = moment(event.end).format('h:mm A')
let time = `${start} - ${end}`
return {time: time, name: event.name}
})
})
console.log('schedule:', schedule)
答案 1 :(得分:0)
正如@charlietfl所说,你的代码不是异步的,所以你不需要Promise。
此代码可以满足您的需求:
const schedule = {}
data.schedule.forEach(item => {
let date = moment(item.date).format('YYYY-MM-DD')
let eventList = []
item.events.forEach(event => {
let start = moment(event.start).format('h:mm A')
let end = moment(event.end).format('h:mm A')
let time = `${start} - ${end}`
eventList.push({time: time, name: event.name})
})
schedule[`${date}`] = eventList
})
对于此输入:
{
schedule: [
{
date: '2017-01-01',
events: [
{
name: 'test',
start: '2017-01-01 10:00:00',
end: '2017-01-01 11:00:00'
}
]
}
]
}
...你明白了:
{
"2017-01-01": [
{
"time": "10:00 AM - 11:00 AM",
"name": "test"
}
]
}