2

I have the below code in Vue3:

    data: function() {
        return {
            testData:[],
        }
    },

    mounted() {
        var testObj = {
            name: 'aniket',
            lastname: 'mahadik'
        }

        for (let index = 0; index < 3; index++) {
            this.testData.push(testObj);
        }
    },

    methods: {
        updateLastName: function(key) {
            this.testData[key].lastname = 'kirve';
        }
    }

When I call updateLastName(1) to update the lastname of only the second element, it's updating the lastname of all the elements.

I tried several ways but found no desired result.

Can someone point out to me what is going wrong here?

Darryl Noakes
  • 2,207
  • 1
  • 9
  • 27
Mak_091
  • 187
  • 1
  • 2
  • 14

1 Answers1

4

It is because you are pushing the reference to the same object in the array so when you update any item in the array you are instead updating every item since it reference the same object.

Either push by cloning the object : testData.value.push({...testObj})

Or put the definition in the push

testData.value.push({ name: 'aniket', lastname: 'mahadik' })

Is JavaScript a pass-by-reference or pass-by-value language?

Pierre Said
  • 3,660
  • 1
  • 16
  • 28