使用js删除localstorage中的json对象 [英] Remove json object in localstorage using js

查看:92
本文介绍了使用js删除localstorage中的json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

假设您已将JSON.parse将本地存储数据存储到一个数组中,则可以像从任何其他数组中一样删除第二个项目-通过弹出它关闭.

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

这篇关于使用js删除localstorage中的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆