Storing items in an array within the local storage

I have been experimenting with different ways to add objects to an array in localstorage without overwriting it, but I haven't found a successful solution yet.

My current code stores objects in an array, but it keeps overwriting itself. Can someone please help me identify what I am missing? (I have a feeling it could be quite 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));
};

Answer №1

Whenever you utilize the setItem method, it will replace the existing item with the new one. To access the previous list, you should use the getItem method, add new content to it, and then update it in localStorage:

function addEntry() {
    // Retrieve any previously saved JSON data from 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));
    // Update allEntries in local storage
    existingEntries.push(entry);
    localStorage.setItem("allEntries", JSON.stringify(existingEntries));
};

For a visual demonstration of the process, check out this fiddle.

Answer №2

Perhaps fetching the existing entries before adding a new one could solve the issue:

let currentEntries = JSON.parse(localStorage.getItem("currentEntries")) || [];
currentEntries.push(newEntry); 
//continue with the rest of the code...

Answer №3

How to Add Objects to an Array in localStorage using Ionic:

var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if(existingEntries == null) existingEntries = [];
var newObject ={name:this.name, 
age:this.age,
city:this.city,
country:this.country,
occupation:this.occupation};

localStorage.setItem('newObject', JSON.stringify(newObject));
existingEntries.push(newObject);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));

Answer №4

let person = {
name: 'John',
age: 35,
number: 123456789,
};
let data = JSON.parse(localStorage.getItem('data_key')) || [];
data.push(person);
localStorage.setItem('data_key', JSON.stringify(data));

Answer №5

Storing data in HTML5 localStorage involves saving key/value pairs, where both the key and value must be strings. If you want to store arrays as keys or values, you will need to encode the array into a JSON string before saving it. When retrieving the data, you'll then need to decode the JSON string back into an array.

const object = {
name: 'ayyan',
age: 29,
number: 03070084689,
};
const arr = JSON.parse(localStorage.getItem('key_name')) || [];
const data = [arr, ...[object]];
localStorage.setItem(JSON.stringify('key', data);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing the width discrepancy in my header section on mobile devices?

Help needed with website responsiveness issue! The site works fine on most screen sizes, but when it reaches around 414px in width, the intro section becomes too wide for the screen. Any ideas on what could be causing this problem? html: <nav id="m ...

Creating a dynamic configuration for service instantiation in Angular 4/5

Currently working on a library that has an AuthModule with an AuthService for managing OAuth2 authentication using oidc-client-js. I want the application using this library to be able to set up the configuration for the OAuth client. One way to do this is ...

Complete a submission using an anchor (<a>) tag containing a specified value in ASP.Net MVC by utilizing Html.BeginForm

I am currently using Html.BeginFrom to generate a form tag and submit a request for external login providers. The HttpPost action in Account Controller // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public Acti ...

`Localhost JSON parsing works fine, but encounters issues on the server``

Although there are many questions about json, none of them seem to answer my specific question. I have a part of my Symfony2 controller that is sending me data. return $this->createResponse(array( 'result' => $users )); die ...

Activate loading state when input changes with VueJS and Vuetify by using @change attribute and setting loading="true"

I am attempting to develop a function that is activated by the @change event on multiple input fields. My goal is to set loading="true" for the targeted input until the axios request (PATCH) is completed. PLEASE NOTE: There are several v-select componen ...

AngularFire Google OAuth failing to retrieve the user's email address

I am trying to retrieve the email address from Google OAuth using AngularFire, but the popup is not requesting permission for the email. This code snippet is from the Firebase Google authentication documentation var ref = new Firebase("https://<your-f ...

Choosing the Best Websocket Libraries for Spring Boot and Angular Communication

In my exploration, I've discovered two methods for linking a Spring Boot backend with an Angular frontend: Using the regular spring-websocket broker with Stomp along with Angular StompJS and SockJS. Utilizing netty-socketio, a Java port of socketIO, ...

When adding the input text value to the <canvas>, the output of .appendTo('<p>' + value + '</p>') is not being shown

Check out my jsfiddle: https://jsfiddle.net/gemcodedigitalmarketing/zn5yLwh3/ I'm trying to append the text from the customText input to the canvas, but it doesn't seem to be working. Yesterday, I successfully appended td and tr to a table, so ...

Move the option from one box to another in jQuery and retain its value

Hey guys, I need some assistance with a jQuery function. The first set of boxes works perfectly with the left and right buttons, but the second set is not functioning properly and doesn't display its price value. I want to fix it so that when I click ...

"Learn how to implement a dropdown menu using Vue.js and Quasar on Cloud Firebase

Hey there, I'm trying to figure out how to retrieve and display a Firebase array in a dropdown using Vue js. Here's what I currently have: I've read some of your articles before, but I'm having trouble displaying the data from an array ...

Plugin for webpack that replaces a specified function with an alternative one

I'm currently working on a webpack plugin that has the ability to analyze code and replace a particular function with another function. Additionally, this plugin will make the new function accessible globally. class PluginName { constructor(local, ...

Transform the usual button into a jQuery button that requires a press and hold action

Within my code, there are two buttons in play. One button triggers the burger menu, while the second button adjusts the size of a div. I am looking to transform only the second button into a hold button that activates after a 3-second delay. code: $doc ...

Tips for incorporating your personal touch while utilizing Snipcart

I have created an ecommerce platform with GatsbyJS and Snipcart, but I am struggling to override the default theme provided by Snipcart. When I try to change the main default CSS through gatsby-config.js, it does not seem to work. Does anyone have a soluti ...

What is a method to omit elements within a nested child element from a selection without relying on the children() function

Here is an example of an element: <div id="foo"> <a href="#" class="some">click me</a> <div id="bar"> <a href="#" class="some">click me too</a> </div> </div> I am facing the challenge of selectin ...

Grunt encountered a critical issue: an undefined function was called

I've been attempting to integrate the npm module node-version-assets into my grunt workflow. Here is a snippet of my grunt file: module.exports = function(grunt){ grunt.registerTask('version-assets', 'version the static assets just ...

What is the best way to run a scheduled task automatically using node-cron?

I have a custom function that saves data to the database using the POST method. When testing it with Postman, I send an empty POST request to trigger the controller. Upon execution, the function triggers two more functions. One of them is responsible for ...

When splitting a string containing multiple integer values using the delimiter ".", the function in Javascript may return inaccurate results

I need help splitting a JavaScript string using the delimiter "." and extracting an exact integer value. <script> var text = "6.100"; var splitText = text.split("."); console.log(splitText[1]); // I want 100 as the output. </script> ...

A handy Vue.js function

I'm currently working on creating a utility method in Vue.js to validate decimal numbers from any input field, but I am facing difficulty in persisting the value internally within Vue.js. In the past, when using jQuery, I used this approach: $(&apos ...

Having performance issues with an HTML5/JavaScript game on Internet Explorer 8

A new game has been developed using html/javascript. Due to confidentiality reasons, the code cannot be fully shared. The game runs smoothly on most browsers except for IE, which poses a challenge. Compatibility with IE8 is essential, despite its limitati ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...