Deletion by index of an article which is in an array of the localStorage vuejs

Viewed 105

I cannot delete an item that is in the localStorage. I created a table to store the added items. I want to delete an article by its index or if possible by its id. thank you for help

deleteOption(){
      this.test = JSON.parse(localStorage.getItem('test'))
      this.test.splice(index, 1)
},

test:[
   {
    id:1,
    item: test item 1
   },
   {
    id:2,
    item: test item 2
   },
   {
    id:3,
    item: test item 3
   },   
]


addItem () {

localStorage.setItem("test",JSON.stringify(this.test))

}


5 Answers

The localstorage getItem method returns a string that should be parsed to an array :

  this.test = JSON.parse(localStorage.getItem('test'))
  this.test.splice(index, 1)

In your case will need to:

  1. Retrieve the string representation you have saved in local storage
  2. Parse the string into an array
  3. Modify the array
  4. Covert the array back into a string
  5. Save the converted string back to local memory.

test:[
   {
    id:1,
    item: test item 1
   },
   {
    id:2,
    item: test item 2
   },
   {
    id:3,
    item: test item 3
   },   
]

localStorage.setItem("test",JSON.stringify(this.test))


function deleteByIndex(index)
{
  var arr = JSON.parse(localStorage.getItem('test'));
  arr = arr.splice(index, 1);
  localStorage.setItem("test",JSON.stringify(arr))
}

function deleteById(id)
{
  var arr = JSON.parse(localStorage.getItem('test'));
  arr = arr.filter(function(item) {
    return item.id !== id
   });
  localStorage.setItem("test",JSON.stringify(arr))
}


test = [
  {
    id: 1,
    item: "test item 1",
  },
  {
    id: 2,
    item: "test item 2",
  },
  {
    id: 3,
    item: "test item 3",
  },
];

testNew = test.filter((item) => item.id !== 2);

console.log(testNew);

It will remove the item with id 2

Who can tell me please for I can not retrieve the index of my object that is in my array in the localStorage?

I have tried for several days now, unable to achieve what I want. I have tried all the methods given to me in this post. One of the methods removes everything from me, and as soon as I add an option I get all the options that I had removed.

Related