"Removing an item from an array stored in localstorage: A step-by-step guide

I need to remove an object from an array and also delete it from local storage. I have attempted to use the splice method but am struggling with how to implement it correctly. Below is the code that I have tried:

 var details = [];

function addEntry() {
   var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
   if (existingEntries == null) existingEntries = [];
   
   // Code for adding a new entry to the array and updating local storage
   
   showEntry();
}

function showEntry() {
   // Code for displaying entries in a table format
   
   // Looping through local storage entries
}

// Other validation functions and event handlers...

function deleteEntry(id) {
   // Code for deleting an entry from the array and updating local storage
}

function clearstorage() {
   localStorage.clear();
   window.location.reload();
}

window.onload = function() {
   showEntry();
};

Answer №1

When you call the deleteEntry function, a new item in localStorage called 'entry' is being set. This means that 'allEntries' is not being updated, which may be why it's appearing incorrectly. Make sure to set all entries again by using localStorage.setItem('allEntries', JSON.stringify(entry));

Don't forget to include the '?' for your variable 'entry'...

Here's how it should look: var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : []; <-- just like this.

This is essentially an 'if else statement'

function deleteEntry(id){
    console.log("aaaaaaaaaaaaaaAAAA");

      var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : [];
        var index;
        for (var i = 0; i < entry.length; i++) {
            if (entry[i].id === id) {
              index=i;
              break;
            }
        }
        if(index === undefined) return 
        entry.splice(index, 1);
        localStorage.setItem('allEntries', JSON.stringify(entry)); <--- ensure it looks like this

    }

Answer №2

One way to update localStorage is by creating a temporary object and then replacing the existing data with it.

 function removeEntry(id){
    console.log("aaaaaaaaaaaaaaAAAA");

      var entry = JSON.parse(localStorage.getItem('allEntries'));
        var temp= [];
        for (var i = 0; i < entry.length; i++) {
            if (entry[i].id !== id) {
              temp.push(entry[i]);
            }
        }
        localStorage.setItem('entry', JSON.stringify(temp));
    }

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

Display a div using Jquery when hovering over it with several classes

I want to create a hover effect where div2 fades in slowly when hovering over div1 within the same container. However, my jQuery code doesn't seem to be working as expected... $(".div").hover(function() { $(this).find(".div2").animate({ opac ...

Three.js not rendering any objects, only displaying a blank black screen

I've encountered a similar issue with a few of my other three.js codes. I've set up the JavaScript within HTML, but the objects aren't appearing on the screen. Every time I run the file, it just shows a black screen. The file is supposed to ...

Tips for entering Tamil characters in text boxes on a form field

Within my form, I have a set of text boxes. I am looking to input text in Tamil font for specific text boxes - around 5 out of the total 10 text boxes in the form. If you know how to enable Tamil font input for multiple text boxes (rather than just one as ...

Controlling HTML5 Video Playback with JavaScript: Pausing at Custom Frames

I need to implement a feature in my web application where I can pause an HTML5 video at specific frames using pure JavaScript, not based on minutes. <video id="media-video" controls> <source id="media-source" src="media/video.mp4" typ ...

Newbie React Developer Struggling to Implement Material-UI Example in React Project, State Functioning Differently from Hooks

I am currently in the early stages of learning React and trying to create a form for a project management web application. For this, I am using material-ui library. I referred to one of the select box component examples from the material-ui documentation ...

What causes the offsetWidth attribute to be zero in an array of elements within the DOM?

I am encountering an issue with a script that sets widths for certain elements in the Dom. Specifically, when I use the code var elements = document.querySelectorAll("p.caption"), the first 12 elements display the correct offsetWidth, but the remaining hal ...

Can the dashstyle be configured for a solid-gauge chart in Highcharts?

I am having trouble making the border dashed on my pie chart. It seems that the solution provided for solidgauge charts is not working as expected. Interestingly, the graph property is undefined for solidgauge charts. I wonder if the dashed style could be ...

I am attempting to build a party planning website but I am encountering an issue where the output is not generating properly. Whenever I click on the submit button, the information I input

I am struggling to create a party planner website and encountering issues with the output. Whenever I click on the submit button, the form just clears out without any feedback or result. Here is what the expected output should be: Validate event date 1: ...

Is there a way for me to invoke a different function that is located external to

I am currently in the process of setting up an event that triggers on any change within the form input class. import React, { useState } from "react"; DealerRegistration extends React.Component { state = { business_type : 'd ...

Node.js can be used to easily set the values of HTML elements

After successfully setting up a node.js connection to my mysql database and being able to retrieve and input data using connection.query(), I now want to display the database information on my HTML elements. Is there an equivalent of getElementById for t ...

Encountered an unexpected forward slash while trying to parse JSON using

When passing a file, why does the `parseJSON` function fail? The file is stored in variable a and then I attempt to parse it using `parseJSON`. var a = "/android/contents/img/uploads/img_2A0.png"; var result = jQuery.parseJSON(a); The error being displa ...

What steps can be taken to ensure that a JavaScript webpack module created for the browser can be safely loaded in a node environment?

I'm currently in the process of modernizing an old JavaScript framework I created, aiming to upgrade it to ES6/module standards. However, I am encountering quite a few challenges along the way. One of the issues I'm facing is related to server-s ...

Sequelize: When attempting to use .get({plain: true})) method, an error is returned indicating that .get is

I'm facing a strange issue as I am able to retrieve only the values of an instance in other parts of my code without any problems. Can you spot what might be wrong with my current code? app.get('/profile', checkAuth, function(req, res) { ...

using node.js to save query results as global variables

Help needed! I'm struggling to pass the results of my query statement to a global variable in order to dynamically configure my jsganntimproved chart. Any suggestions on what could be going wrong? In the snippet below, the console.log(taskItem) retur ...

Managing multiple Socket.io connections upon page reload

I am currently developing a real-time application and utilizing Socket.io for its functionality. At the moment, my setup involves receiving user-posted messages through the socket server, saving this data to a MySQL database via the controller, and then b ...

Navigating through Switch cases and If Statements with multiple arguments can be complex for beginners in the world of JavaScript

Hi there, I have a specific case that I'm struggling to find a solution for. I am using Angular with a Firebase back-end to retrieve true or false values from a variable called ref. The variable contains 4 properties with either true or false values - ...

"NgFor can only bind to Array objects - troubleshoot and resolve this error

Recently, I've encountered a perplexing error that has left me stumped. Can anyone offer guidance on how to resolve this issue? ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supp ...

Attempting to enable a checkbox using a controller located in a separate controller

I am attempting to trigger a checkbox from a separate controller. Suppose I have a card called information technology under one controller, and when clicked, it should redirect to another page that contains a checkbox for information technology managed by ...

I'm curious about how to properly escape single quotes when passing a variable in a Java argument call using Karate DSL. Can you help

As part of our API project at work, I am looking to incorporate database calls into our end-to-end process. One challenge I am facing is how to handle single quotes within a variable that is passed as an argument in an assert method. I have attempted the f ...

Expanding Lists in Bootstrap 3: A Step-by-Step Guide

I have been experimenting with Bootstrap's Example accordion code, which can be accessed via this link: http://jsfiddle.net/qba2xgh6/18/ <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel ...