我在 vuejs 观察器中使用 forEach 来修改我的对象数组。目标是在每个对象最后获得新值 (end_time)。 allChapters 已经包含了我想要的所有内容,但我似乎无法将其写回原始对象。
watch: {
episode (episode) {
episode.chapters = episode.chapters.forEach((chapter, index, allChapters) => {
let endTime = ''
if (allChapters[(index + 1)]) {
endTime = allChapters[(index + 1)].start_time
} else {
endTime = '99:99:99'
}
console.log(index + ': ' + chapter.start_time + ' / ' + endTime)
allChapters[index] = {
'start_time': chapter.start_time,
'title': chapter.title,
'end_time': endTime
}
})
}
},
最佳答案
forEach
不会返回任何内容,因此您最终将 undefined
分配给 episode.chapters
。
删除episode.chapters =
episode (episode) {
episode.chapters.forEach((chapter, index, allChapters) => { ... })
或使用返回新数组的map
watch: {
episode (episode) {
episode.chapters = episode.chapters.map((chapter, index, allChapters) => {
let endTime = ''
if (allChapters[(index + 1)]) {
endTime = allChapters[(index + 1)].start_time
} else {
endTime = '99:99:99'
}
console.log(index + ': ' + chapter.start_time + ' / ' + endTime)
return {...chapter, 'end_time': endTime};
})
}
},
关于javascript - 将 forEach 循环中内置的数组数据写回原始对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275385/