尝试从本地存储密钥中删除特定值 [英] Trying to remove particular value from local storage key

查看:51
本文介绍了尝试从本地存储密钥中删除特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串形式的本地存储密钥.这是它的外观:

I have a local storage key in the form of a string. Here's how it looks :

var key = localStorage.getItem(localStorage.key(0));
console.log(key);

在控制台上打印:

 {"logged_user":"myname","abcDatatitle":"AHarmbca Reports","abcData":"300"};

仅供参考: console.log(typeof key);打印字符串

我要删除此部分"abcDatatitle":"AHarmbca Reports" ,以便键(console.log(key);)如下所示:

I want to remove this part "abcDatatitle":"AHarmbca Reports" so that the key (console.log(key);) would look like the following :

{"logged_user":"myname","abcData":"300"};

我可以像这样使用javascript的 replace 函数

I could use the replace function of javascript like this,

key = key.replace("abcDatatitle",""); 

,但这只会删除此 abcDatatitle 部分.考虑到以下情况,我如何确保整个"abcDatatitle":"AHarmbca Reports" 都消失了该值 AHarmbca报告是动态值.

but this would remove only this abcDatatitle part. How can I make sure that the whole part "abcDatatitle":"AHarmbca Reports" is gone considering the fact that this value AHarmbca Reports is a dynamic value.

推荐答案

使用 JSON.parse ,然后删除对象密钥,然后使用 JSON.stringify

use JSON.parse then delete the object key, then use JSON.stringify

//convert string to object
var key = localStorage.getItem(localStorage.key(0))
var objKey = JSON.parse(key)
delete objKey.abcDatatitle

//parse to string again
var strKey = objKey = JSON.stringify(objKey)

// update localStorage
localStorage.setItem(localStorage.key(0), strKey)

这篇关于尝试从本地存储密钥中删除特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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