清除特定密钥的localstorage

时间:2016-08-09 06:42:23

标签: jquery local-storage

我已经在localstorage中存储了一些信息,数据存储如下:

#firstWordCategory#

enter image description here

现在我想在8中为特定的id设置MsgCount = 0:user_abc-com

那怎么做?

2 个答案:

答案 0 :(得分:1)

s是您的localStorage,jsfiddle

var s = "[{\"id\":\"user_abc-com\",\"MsgCount\":8},{\"id\":\"user2_abc-com\",\"MsgCount\":16}]";
var s_obj = JSON.parse(s); // parsing it from string to object

s_obj.forEach(function(v, k) { // iterate through array
    if(v.id == 'user_abc-com') s_obj[k].MsgCount = 0 // change value
});

s = JSON.stringify(s_obj); // switching to string again (ready to save in localStorage)

答案 1 :(得分:0)

只需使用新值更新元素:



var messages = [
  {"id": "user_abc-com", "MsgCount": 8},
  {"id": "user2_abc-com", "MsgCount": 16}
];

localStorage.setItem('MessageCount', JSON.stringify(messages));

// ----------- //

var messages = JSON.parse(localStorage.getItem('MessageCount'));
messages[0]['MsgCount'] = 0;
localStorage.setItem('MessageCount', JSON.stringify(messages));

// ----------- //

console.log(localStorage.getItem('MessageCount'));