I am trying to remove all items from my array that contains a specific word for example, "_OJ" by using a button. How can i modify my code to do that?
new Vue({
el: "#app",
data: {
activeselected:[{"Identifier":"1396",
"name":"LMM_330_OJ_M15_MASTER"
},{"Identifier":"1396",
"name":"LMM_330_OJ_M15_MASTER"
},
{"Identifier":"139s26",
"name":"LMM_320_OK_M15_MASTER"
}]
},
methods: {
removeOk: function(activeselected){
this.activeselected.splice(index, 1);
},
removeOJ: function(activeselected){
this.activeselected.splice(index, 1);
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{activeselected}}
<br>
<br>
<button v-on:click="removeOJ(index)">
Remove Anything with _OJ
</button>
<button v-on:click="removeOk(index)">
Remove Anything with _OC
</button>
</div>
CodePudding user response:
Data have to be function, and you can use filter:
new Vue({
el: "#app",
data() {
return {
activeselected:[{"Identifier":"1396", "name":"LMM_330_OJ_M15_MASTER"}, {"Identifier":"1396", "name":"LMM_330_OJ_M15_MASTER"}, {"Identifier":"139s26", "name":"LMM_320_OK_M15_MASTER"}]
}
},
methods: {
remove(id){
this.activeselected = this.activeselected.filter(a => !a.name.includes(id));
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{activeselected}}
<br>
<br>
<button v-on:click="remove('_OJ')">
Remove Anything with _OJ
</button>
<button v-on:click="remove('_OK')">
Remove Anything with _OC
</button>
</div>
CodePudding user response:
We need a function that returns a bool that's true when any value of an object contains a substring. Something like this will do it:
const valuesHaveSubstring = (o, s) =>
Object.values(o).some(value => value.includes(s));
Demo:
const valuesHaveSubstring = (o, s) => Object.values(o).some(value => value.includes(s));
new Vue({
el: "#app",
data: {
activeselected: [{
"Identifier": "1396",
"name": "LMM_330_OJ_M15_MASTER"
}, {
"Identifier": "1396",
"name": "LMM_330_OJ_M15_MASTER"
},
{
"Identifier": "139s26",
"name": "LMM_320_OK_M15_MASTER"
}
]
},
methods: {
remove: function(string) {
this.activeselected = this.activeselected.filter(o => !valuesHaveSubstring(o, string))
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{activeselected}}
<br>
<br>
<button v-on:click="remove('_OJ')">
Remove Anything with _OJ
</button>
<button v-on:click="remove('_OxxxC')">
Remove Anything with _OC
</button>
</div>