[Vuejs]-Vue computed property overwriting global state without vuex

0👍

Your problem isn’t that you’re modifying the array, but that you’re modifying the objects within the array. You change the scoreHistory and score property of each item in the array. What you want to do instead is create a new array (I recommend using map) where each item is a copy of the existing item plus a new score property.

filteredScores () {
  if(!this.people) {
    return
  }

  let timeWindow = 30 //days
  const windowStart = moment().subtract(timeWindow,'days').toDate()

  return this.people.map(p => {
    let filteredScores = p.scoreHistory.filter(score => moment(score.date.toDate()).isSameOrAfter(windowStart,'day'))

    //calculate new score
    let score = filteredScores.reduce(function(sum, item) {
      return sum + item.voteScore
    }, 0)

    // Create a new object containing all the properties of p and adding score
    return {
      ...p,
      score
    }
  }
})

Leave a comment