0

I want to delete an item based on its id. I retrieve id from the cell where I click but I don't know how to retrieve id in the array to be able to compare it to that of the click to delete only the one selected and not all of the array, I'm not sure which method to use

My item.json

[{
    "id": "e3c387fd-7cf1-4d5b-9825-cef745c0ab99",
    "name": "item 1",
    "fans": {},
    "cell": [{
        "id": "e2021621-9c74-4960-bf47-f6ad917ee40b",
        "name": "cell 1 item 1",

      },
      {
        "id": "d5129940-716c-47a3-81b5-f2c90e69b602",
        "name": "cell 2 item 1",

      }
    ]
  },
  {
    "id": "79fe939b-4c64-4b73-bebd-6563f445920c",
    "name": "item 2",
    "fans": {},
    "cell": [{
        "id": "7b6b57c6-7b72-4a14-8932-51fc2e5f9b75",
        "name": "cell 1 item 2",

      },
      {
        "id": "b579f94f-605e-4c7a-a8c5-3aad9bfec9e2",
        "name": "cell 2 item 2",

      }
    ]
  }
]

My function

trashItem(id) {
  this.cellsListsData = this.cellsListsData.filter(cell => {
    cell.id === id, console.log(cell.id, id);
  });
}

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
  • 2
    You are not returning from the filter callback. You can skip the `return` if you don't have the `{}` in the arrow function (implicit return). And your condition should be `!== id` if you want to exclude a specific id. So, `cell => { console.log(cell.id, id); return cell.id !== id }` – adiga Apr 02 '21 at 07:14

2 Answers2

0
this.cellsListsData = this.cellsListsData.filter(function(element) {
    return element.id !== id;
  });

or Just Get the index of it and then this.cellsListsData.splice(index, 1);

Toxy
  • 696
  • 5
  • 9
0

This would require traversing through the whole array and finding the index of object with the given id. Once you find the id, you can simply splice the array from that index with offset 1. Below is a quick snippet for doing that.

var index_to_delete;
data.forEach(function(value, index) {
   if (value.id == id_of_clicked_element) {
     index_to_delete = index;
   };
});
data.splice(index_to_delete, 1);

Note: Using filter will create a new array. So, if you are referencing the data array in some other variables, they will not get the new array. So, I recommend using the filter solution with caution. Also, some answers say to delete element at that index. This would remove that index from array and your array will be rendered inconsistent.

Shadab
  • 46
  • 4