Remove json object in localstorage using js

2019-09-11 08:03发布

问题:

[{'id':1,'content':'something'},{'id':2,'content':'something diff'},{'id':3,'content':'something diff'}]

by localStorage.getItem('data') I got the above json object, but how to delete the id 2 item?

回答1:

Assuming you've JSON.parse'd your local storage data into an array, you can remove the second item like you would from any other array- by popping it off.

var data = localStorage.getItem('data');
// At this point, data is either null or a string value.
// To restore the string to an Array you need to use JSON.parse
if (data) {
  data = JSON.parse(data);

  // At this point you can use Array methods like pop or splice to remove objects.
}
// At this point, your Array will only contain the first item.
// If you want to write it back to local storage, you can like so:
// Be sure to use JSON.stringify so it can later be restored with parse.
localStorage.setItem('data', JSON.stringify(data));


回答2:

This will turn "data" into a javascript object and remove the last item (assuming this is always an array):

var data = localStorage.getItem('data');
if (data) {
   data = JSON.parse(data);
   data.pop();
}