Reputation: 2860
I have stored some information in localstorage and the data storing like :
localStorage :
MessageCount : "[{"id":"user_abc-com","MsgCount":8},{"id":"user2_abc-com","MsgCount":16}]"
Now here I want to make MsgCount = 0 from 8 for a specific id : user_abc-com
So how to do that ?
Upvotes: 0
Views: 66
Reputation: 43557
Simply update your element with new value:
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'));
Upvotes: 0
Reputation: 2734
s is your 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)
Upvotes: 1