如何在JSON中更改localStorage中键的值?

时间:2015-03-28 09:59:58

标签: javascript json html5 local-storage

我有一个日历。日历中的事件被写为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中。

E.g。

  //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中引用“描述”(“事件”?“参与者”?...)来重新设置值?

1 个答案:

答案 0 :(得分:0)

您将events数组存储为localStorage中的字符串。如果要更改事件中的任何值,则必须替换存储在"事件"中的字符串值。键入localStorage - 换句话说,替换events数组的整个值。

实际上,您可以使用以下方法提取值:

events = JSON.parse(localStorage.getItem('events'))

更改要更改的事件,然后使用以下命令保存:

localStorage.setItem('events', JSON.stringify(events)); 

如果您正在考虑如何在"事件"中更改单个事件的价值?在localStorage中,您只有一个键" events",因此您只能将该值更改为整体。