0

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?

2
  • I notice you use the word "efficient" in your question. Are we talking about tens of thousands of items here, or just a few? Commented Sep 16, 2019 at 19:08
  • Yeah sorry that was a bit misleading, by efficient I just meant that it would be much easier if I didn't have to reassign each property to itself. Just a few items. Commented Sep 16, 2019 at 19:30

1 Answer 1

2

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

Comments

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.