twoam
twoam

Reputation: 892

Remove whole object from array in vue

Right now I have an array with multiple companies.

Like this but only 1:

[{
    "id": 4,
    "name": "Lorem",
    "description": "Lorem ipsum"
}]

I loop through the companies and pass the company with the delete function.

<a @click="deleteCompany(company)"><i class="fa fa-trash" aria-hidden="true"></i></a>

deleteCompany(company) {
    Vue.delete(company, 'name');
}

As of right now it only deletes the name.. but how do I delete the whole object?

Upvotes: 0

Views: 49

Answers (1)

Bert
Bert

Reputation: 82439

Assuming your array of companies is in the data for the Vue, you would remove it this way:

deleteCompany(company) {
    // find the index of the company object in the companies array
    const where = this.companies.findIndex(c => c === company)
    // splice the object from the array
    this.companies.splice(where, 1)
}

This could be shortened a bit if you chose to pass the index of the company to the function instead of the company itself.

You could also use Vue.delete, but it is not necessary in this case; splice will do. If you wanted to use Vue.delete, it would look like this: Vue.delete(this.companies, where).

Upvotes: 1

Related Questions