[Vuejs]-How can I overwrite an existing array item when pushing new data?

1👍

Can’t you just assign a new array? I.e.

this.fullSelectedCar = [{
  ...result.data
  ...
}];

Alternatively, you can just clear the array before you push, a simple way in JS is to set length to 0:

this.fullSelectedCar.length = 0
this.fullSelectedCar.push({...});

Seems simple enough. Let me know if I am missing something.

0👍

Simply check, if no data is present in the array, then push the clicked else override the first object always.

Important- Use $set to make modifications in the array so it would be reactive.

new Vue({
  el: "#app",
  data() {
    return {
      fullSelectedCar: [],
      cars: [
        {
          id: 1,
          name: "Volvo"
        },
        {
          id: 2,
          name: "Toyota"
        },
        {
          id: 3,
          name: "Honda"
        }
      ]
    }
  },
  methods: {
    pushToArr(payload) {
      // If no data is present in the array
      if(!this.fullSelectedCar.length) {
        this.fullSelectedCar.push(payload)
        return;
      } 
      // override the first index data every time
      this.$set(this.fullSelectedCar, 0, payload);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  fullSelectedCar - {{ fullSelectedCar }}<br><br>
  <b>Click on any car</b>
  <ul>
    <li v-for="car in cars" @click="pushToArr(car)">{{ car.name }}</li>
  </ul>
</div>

Leave a comment