Home > Software engineering >  All values getting upadted when tried to update single element in an associative array in Vue 3
All values getting upadted when tried to update single element in an associative array in Vue 3

Time:01-20

I have 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) method to update last name of only second element, its getting updated lastname of all elements.

I tried several ways but no desired result found.

Can some one point me what is going wrong here?

CodePudding user response:

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?

  • Related