【问题标题】:How do I change the value of a key in localStorage inside JSON?如何更改 JSON 中 localStorage 中键的值?
【发布时间】:2015-06-01 16:12:16
【问题描述】:

我有一个日历。日历中的事件以 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 中的“描述”(“事件”?“参与者”?...)来重新设置值?

【问题讨论】:

    标签: javascript json html local-storage


    【解决方案1】:

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

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

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

    更改您要更改的事件,然后使用:

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

    如果您正在考虑如何仅更改 localStorage 中“事件”中单个事件的值,那么您只有一个键“事件”,因此您只能更改整个值。

    【讨论】:

    • 当我用 localStorage.setItem('events', JSON.stringify(events)); 替换值时它在 localStorage 中再添加一个事件,但不会删除前一个事件,然后我在 localStorage 中有两个日期相同的事件,尽管我的日历应该每天只有一个事件。但用户只能看到“新”事件。所以看起来没问题,但我想从 localStorage 中删除以前的“事件”(或任何更改的部分)。
    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 2021-06-29
    • 2019-10-04
    • 2021-02-14
    相关资源
    最近更新 更多