Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding objects to array in localStorage

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 find at least one of them.

Got this code to store objects in array but it's overwriting itself. May anyone show me what am I missing? (And I'm afraid I could be missing a lot).

function addEntry() {
    var entryTitle = document.getElementById("entryTitle").value;
    var entryText = document.getElementById("entryText").value;
    var entry = {
        "title": entryTitle,
        "text": entryText
    };
    localStorage.setItem("entry", JSON.stringify(entry));
    var allEntries = [];
    allEntries.push(entry);
    localStorage.setItem("allEntries", JSON.stringify(allEntries));
};
like image 949
Joh Smith Avatar asked Oct 28 '13 12:10

Joh Smith


People also ask

How do I push an object into an array in localStorage?

// Get the existing data var existing = localStorage. getItem('myFavoriteSandwich'); // If no existing data, create an array // Otherwise, convert the localStorage string to an array existing = existing ? existing. split(',') : []; // Add new data to localStorage Array existing.

Can you store an array of objects in localStorage?

The localStorage API in browsers only supports adding information in a key:pair format and the key and the pair should be of type string thus native objects or arrays cannot be stored in the localStorage .

Can we store objects in localStorage?

In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON. parse method.


1 Answers

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.

like image 68
CodingIntrigue Avatar answered Oct 29 '22 00:10

CodingIntrigue