How to delete an item from an object using an internal ID (Vue-2)

Asked

Viewed 591 times

3

I have an object with the following format:

[  
   {  
      "id":1,
      "name":"exemplo1",
      "email":"exemplo1"
   },
   {  
      "id":2,
      "name":"exemplo2",
      "email":"exemplo2"
   }
]

I need to delete an item from this object using ID intern of his.

Sort of like this:

delete item da lista onde item.id == id

I am using the Vue-2 framework to display in a table.

<tr v-for="{item, index} in list">
     <div @click="delete(item.id)"></div>
</tr>

important: delete the item using index does not serve, I need it to be with the ID.

  • Where does this array? no data of component? in props? or comes from the server? And what is the action that makes this removal? is a methods?

  • @Sergio yes, this within a date and need to remove with methods

  • strange placement importante: deletar o item usando o index não serve, eu preciso que seja com o ID.

1 answer

5


One way to do this would be to go through the entire list until you find the searched id, then remove that element, follow an example

<div id="app">
    <div v-for="(item, index) in lista" :key="index">
        <span>{{ item.valor }}</span><button type="button" @click="removerPorId(item.id)">Remover</button><br>
    </div>
</div>

var vm = new Vue({
    el: '#app',
    data: {
        lista: [{
            id: 1,
            valor: 'Indice 1'
        },
        {
            id: 2,
            valor: 'Indice 2'
        },
        {
            id: 3,
            valor: 'Indice 3'
        },
        {
            id: 4,
            valor: 'Indice 4'
        },
        {
            id: 5,
            valor: 'Indice 5'
        }]
    },
    methods: {
        removerPorId: function (id) {
            var _vm = this; //Adicionando a instância à uma variável, para que possa ser acessada dentro do forEach`
            this.lista.forEach(function(el, index) {
                if(el.id === id)
                    _vm.lista.splice(index, 1);
            })
        }
    }
});

Another way would be to use the function filter() to filter all elements that are different from the one you want to remove (suggestion from Sergio)

//Apenas a função removerPorId reescrita com o filter
removerPorId: function (id) {
    this.lista = this.lista.filter(function(el) {
        return el.id !== id;
    });
}
  • Thanks for the help, I was suffering from it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.