使用js删除localstorage中的json对象

时间:2015-03-23 16:13:29

标签: javascript json local-storage

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

by localStorage.getItem('data')我得到了上面的json对象,但是如何删除id 2项呢?

2 个答案:

答案 0 :(得分:1)

假设您已将JSON.parse将本地存储数据存储到数组中,您可以通过弹出它来删除第二项,就像从任何其他阵列中删除一样。

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

答案 1 :(得分:0)

这会将“数据”转换为javascript对象并删除最后一项(假设这总是一个数组):

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