Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

owen2jan's avatar

remove object from array of objects

I have an array of objects in the data option. How can I remove an object from it like in the example below.

in the script

data(){return{
	arr: [
		{
			id:'1'
			name:'test'
		}
		{
			id:'2'
			name:'test2'
		}
	]
}},
methods:{
	remove(item){
		let temp = this.arr.filter(a => a.id != item.id)
		this.arr = temp
	}
}

in the template

<p v-for="a in arr" :key="a.id">
{{a.name}}
<image src="/images/close.svg" @click="remove(a)">
</p>
0 likes
7 replies
ramonrietdijk's avatar
Level 30

I would recommend using the splice function. Start by adding the index to your loop.

<p v-for="(a, index) in arr" :key="a.id">
    {{a.name}}
    <image src="/images/close.svg" @click="remove(index)">
</p>

And splice your JavaScript array.

remove(index) {
    this.arr.splice(index, 1);
}
MaverickChan's avatar

@ramonrietdijk

your code will fail, because , the index will change should be like this

removeitem (m) {      

        this.arr.splice(this.arr.indexOf(m),1);

    }
ramonrietdijk's avatar

@MaverickChan How would my code fail? When splicing the array an item is removed and the indexes are reset, so is the reference in the click event. As it is used in the loop, the index is always available.

MaverickChan's avatar

@ramonrietdijk index reset is the problem , if you delete more than one record, you will see the template rendering wrong records.

He is using v-for index , not the array index, you are making the same mistake.

ramonrietdijk's avatar

@MaverickChan It is indeed true that the indexes are different when removing items since the array is modified. The index in the v-for is still the array index - but of the "modified" array. It is not removing wrong records when using the index from the loop. It could only cause problems when using the index of the original array (separately stored from this.arr) but I don't see the point of that as it is not used here.

Is that what you mean?

MaverickChan's avatar

@ramonrietdijk my solution is to avoid any mistake. In this case , maybe you can say it's ok, but what about next time ? What about another case? Just wanna do the right thing , this could save you a lot of time in the future.

Please or to participate in this conversation.