adding objects to array in localStorage

后端 未结 5 1809
轮回少年
轮回少年 2021-01-11 10:44

Ok, I\'ve tried to follow examples here, I know there might be a few different ways of adding objects to an array in localstorage and not overwriting it but I\'m failing to

5条回答
  •  一生所求
    2021-01-11 11:36

    When you use setItem it overwrites the item which was there before it. You need to use getItem to retrieve the old list, append to it, then save it back to localStorage:

    function addEntry() {
        // Parse any JSON previously stored in allEntries
        var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
        if(existingEntries == null) existingEntries = [];
        var entryTitle = document.getElementById("entryTitle").value;
        var entryText = document.getElementById("entryText").value;
        var entry = {
            "title": entryTitle,
            "text": entryText
        };
        localStorage.setItem("entry", JSON.stringify(entry));
        // Save allEntries back to local storage
        existingEntries.push(entry);
        localStorage.setItem("allEntries", JSON.stringify(existingEntries));
    };
    

    Here is a fiddle which demonstrates the above.

提交回复
热议问题