Home » vue » Changing one attribute in an array of objects in Vue.js

Changing one attribute in an array of objects in Vue.js

Posted by: admin November 26, 2021 Leave a comment

Questions:

Let’s presume I have an array structure that roughly looks like this:

var test = [
{
    name: "Patrick",
    age: 34,
    country: "USA"
},
{
    name: "Manuel",
    age: 26,
    country: "Germany"
}]

If I want to change one property for every element in the array, I can’t just change it by looping through the whole array and doing obj.country = "Germany (if I wanted to change the country of every object to Germany), since Vue.js won’t register the changes according to the documentation (and I tested it myself, it indeed doesn’t work). The only way of changing it that I’ve come up with is doing something like this (assuming that test is a data property):

for (var e in this.test) {
    this.$set(this.test, e, {
        name: this.test[e].name,
        age: this.test[e].age,
        country: "Germany"
    })
}

However, this doesn’t seem like a very efficient way to do it, because if I, for example, decide to add another property to all of the array elements or make some other changes, I’d have to search all ocurances of this kind of for-loop and include this change, which strikes me as very inefficient. Is there a way to use this.$set while only changing one element in the object and leaving the other ones unchanged?

Answers:

Assuming this is component state, an easy way to change everything is just to reassign the array:

this.test = this.test.map(item => ({
  ...item,
  country: 'Germany',
}));

If it was a prop, you could do something similar with a computed property:

computed: {
  allGermany() {
    return this.test.map(item => ({
      ...item,
      country: 'Germany',
    }));
  }
}