Skip to content Skip to sidebar Skip to footer

Remove Object From Array Filtered By An Id Vuejs

I am doing a function to delete more then one record based on the checkboxes selected but as I receive the ID (not the full object) I am facing problems to remove it from the array

Solution 1:

There are two main problems with your code, one of them which is already highlighted by JS Bin:

  1. You shouldn't define functions within a loop if they reference the looped value. See here why. (Unless you wrap it in an IIFE or use let to define your loop variable).

  2. You are comparing an id of the type Number with a selected entry of the type String with the !== operator. This wont work, because !== does a strict equal. (You can see that in your container output).

To fix the first issue, I would forgo the outer for loop entirely and use indexOf to check if the current val.id exists in this.selected.

this.selected.indexOf(val.id) === -1;

This wont work yet, because we are still comparing a String with a Number in indexOf. So we have to transform the val.id into a string (which fixes problem #2).

this.selected.indexOf(val.id.toString()) === -1;

Which leaves us with the following code (after removing the for loop):

new Vue({

  el: 'body',

  data: {
    record: {},
    selected: [],
    list: [
        { name: 'Google', id: 1, cat: 'Category 1' },
        { name: 'Facebook', id: 2, cat: 'Category 2' },
      ],
  },

  methods: {
    deleteSelected: function () {
        this.list = this.list.filter(function(val, i) {
            returnthis.selected.indexOf(val.id.toString()) === -1;
        }, this);
     }
  }

});

Note: In order to use the this context of the vue component inside the filter function, we pass it in as the second argument.

JS Bin

Post a Comment for "Remove Object From Array Filtered By An Id Vuejs"