0
[{'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?

Dean Jason
  • 105
  • 1
  • 1
  • 9
  • 2
    You decode the JSON string, manipulate the object, and then encode and store it back into localstorage again … – CBroe Mar 23 '15 at 16:23
  • Almost a duplicate of [How do I remove an object from an array with JavaScript?](http://stackoverflow.com/q/3396088/218196) – Felix Kling Mar 23 '15 at 16:29

2 Answers2

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));
bvaughn
  • 13,300
  • 45
  • 46
0

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();
}
KJ Price
  • 5,774
  • 3
  • 21
  • 34
  • .pop remove the last item? I want to match with the id. – Dean Jason Mar 23 '15 at 16:19
  • I just noticed @brianvaugn's answer. He beat mine I think. Weird that ours are identical. – KJ Price Mar 23 '15 at 16:20
  • Not that weird! There's only 1 obvious way to parse local storage data and remove the last item from an Array. :) – bvaughn Mar 23 '15 at 17:38
  • Haha, yes. Still funny. I was looking at your code for about 20 seconds trying remember when I added `data` back into `localStorage`. I thought I was looking at my code! :D – KJ Price Mar 23 '15 at 18:33