Remove Object From Array Filtered By An Id Vuejs
Solution 1:
There are two main problems with your code, one of them which is already highlighted by JS Bin:
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
letto define your loop variable).You are comparing an id of the type
Numberwith a selected entry of the typeStringwith the!==operator. This wont work, because!==does a strict equal. (You can see that in yourcontaineroutput).
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.
Post a Comment for "Remove Object From Array Filtered By An Id Vuejs"