Dean Jason
Dean Jason

Reputation: 105

Remove json object in localstorage using js

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

Upvotes: 0

Views: 1275

Answers (2)

bvaughn
bvaughn

Reputation: 13487

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));

Upvotes: 1

KJ Price
KJ Price

Reputation: 5964

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();
}

Upvotes: 0

Related Questions