2

I want to use a delete function to remove a specific object in an array.

I tried the splice() method but it removes just the first array no matter which objects I clicked on

Here is the code for object with a v-for method

 <li v-for=" skill in skills" :key="skill.id">
        {{skill.skill}}
        <i class="fa fa-minus-circle v-on:click="remove(skill)"></i>
      </li>

here is the Skill.vue

 <script>
import uuid from "uuid";
export default {
  name: "Skills",
  data() {
   return {
  skill: "",
  skills: [
    { id: uuid.v4(), skill: "Vue.js" },
    {
      id: uuid.v4(),
      skill: "Javascript"
    },
    {
      id: uuid.v4(),
      skill: "Rails"
    }
  ]
 };
},
methods: {
addSkill() {
  this.$validator.validateAll().then(result => {
    if (result) {
      this.skills.push({ skill: this.skill, id: uuid.v4() });
      this.skill = "";
    }
  });
},
remove(id) {
  this.skills.splice(id, 1);
 }
}

};

How can I construct the method

remove(id) {
  this.skills.splice(id, 1);
 }

to delete the specific object?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
foliwe83
  • 546
  • 1
  • 7
  • 24
  • [`splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) takes the index at which to start removing, not the value. Use [`indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) or [`findIndex`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) to get the appropriate value to put into `splice`. – Heretic Monkey Jan 24 '19 at 19:26
  • Possible duplicate of [Remove array element based on object property](https://stackoverflow.com/questions/15287865/remove-array-element-based-on-object-property) – Heretic Monkey Jan 24 '19 at 19:27

2 Answers2

2

To use splice() you should be passing the index of the item as parameter. To remove an item based on a property, consider using filter() instead.

Template should be:

<li v-for="skills in skill" :key="skill.id">
  {{skill.skill}}
  <i class="fa fa-minus-circle v-on:click="remove(skill.id)"></i>
</li>

And the method:

remove(id) {
  this.skills = this.skills.filter(skill => skill.id !== id);
}

It will return a copy of the array without the items where skill.id !== id evaluates to false.

1

you should pass the index :

array.splice(index, howmany, item1, ....., itemX)

splice

<li v-for=" (skills,index) in skill" :key="skill.id">
        {{skill.skill}}
        <i class="fa fa-minus-circle v-on:click="remove(index)"></i>
      </li>

so :

remove(index) {
  this.skills.splice(index, 1);
 }
Aziz.G
  • 3,599
  • 2
  • 17
  • 35