0

I'm using forEach in a vuejs watcher to modify my array of objects. Goal is to have the new value (end_time) in each object at the end. allChapters already contains everything I want but I can't seem to get it written back to the original object.

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
      }
    })
  }
},
1
  • you should accept the answer if it solved your problem. Commented May 10, 2018 at 15:51

1 Answer 1

1

the forEach does not return anything, so you end up assigning undefined to the episode.chapters.

Either remove the episode.chapters =

episode (episode) {
    episode.chapters.forEach((chapter, index, allChapters) => { ... })

or use map which returns a new array

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};
    })
  }
},
Sign up to request clarification or add additional context in comments.

1 Comment

looks like I didn't see the obvious one. Thanks for helping out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.