我有一本日历。日历中的事件以 JSON 形式编写并存储在 localStorage 中,如下所示:
key = events //All events as Object
value =
{
"Date":"31-3-2015",
"Event":"Football match",
"Participants":"Italy - Germany",
"Description":"Support our team with your friends!"},
"Date":"2-4-2015",
"Event":"First-night play",
"Participants":"Famous actors",
"Description":"Going out to the theatre with my gf"}
etc...
我还可以更改日历中事件的每一行。但随后我需要将一个新值存储在 localStorage 中。
例如
//Old version
""Date":"2-4-2015",
"Event":"First-night play",
"Participants":"Famous actors",
"Description":"Going out to the theatre with my gf"}
//Edited version
"Date":"2-4-2015",
"Event":"First-night play",
"Participants":"Famous actors",
"Description":"Let my gf visit the play alone"}
这是我添加新事件或编辑现有事件的函数:
var addNewEvent = function() {
var events = JSON.parse(localStorage.getItem('events')) || [];
events.push(
{Date: storageNewDate,
Event: storageEvent,
Participants: storageParticipants,
Description: storageDescription});
localStorage.setItem('events', JSON.stringify(events));
};
但它仅适用于 localStorage(如果您决定用新事件替换现有事件,则不会重置 localStorage),尽管从视觉上您会在日历单元格中看到新事件。
那么,在我的情况下,如何引用 localStorage 中的“描述”(“事件”?“参与者”?...)来重新设置值?
最佳答案
您将事件数组作为字符串存储在 localStorage 中。如果要更改 events 中的任何值,则必须替换 localStorage 中“events”键中存储的字符串值 - 换句话说,替换 events 数组的整个值。
实际上,您可以使用以下方式提取值:
events = JSON.parse(localStorage.getItem('events'))
更改您想要更改的事件,然后使用以下命令保存它:
localStorage.setItem('events', JSON.stringify(events));
如果您正在考虑如何更改 localStorage 中“事件”中单个事件的值,那么您只有一个键“事件”,因此您只能更改整个值。
关于javascript - 如何更改 JSON 中 localStorage 中键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29315829/