What is the correct method to remove an item from local storage?

Using localStorage, I have stored multiple objects in an array. Is there a way to remove just one object from this array?

If I use

localstorage.removeItem(keysofthelocalstorage)
, I can delete the entire array, but I specifically want to remove only certain items.

For instance, if the key for my entry in local storage is basketContent and the value looks like [{object1},{object2},{object3}], how can I delete {object1}? Do I need to assign a different key to reference this object in the array?

I'm able to access the object I wish to delete with a "delete" button click event, but actually removing it has been troublesome. I've attempted using slice without satisfactory results. Here's the relevant portion of my code:

let basketContent = JSON.parse(localStorage.getItem("basketContent")); // Parses JSON data
// console.log(basketContent);
if (basketContent !== null) { 
   for (let i = 0; i < basketContent.length; i++) {
      const tabsLine = document.createElement("tr");
      const deleteButton = document.createElement("button");
      deleteButton.setAttribute("class", "btn btn-danger mt-1") ;
      deleteButton.innerHTML = "delete";
      const tbody = document.getElementById("bodytabs");
      tbody.appendChild(tabsLine);
      tabsLine.appendChild(deleteButton);
      console.log(basketContent);
  
      /////////////////////// on click ///////////////////////
      deleteButton.addEventListener("click", function() {
         console.log(baksketContent); // Displays the array of objects
         console.log(basketContent[i]); // Displays the specific object
      });
   }
} else {
   console.log("empty busket");
}

Answer №1

To begin, you will need to parse the JSON string that is saved in localStorage. Remove the specified object from the array and then save the updated array back into localStorage.

const data = JSON.parse(localStorage.getItem('cartItems'));
data.splice(data.indexOf(/*your object*/), 1);
localStorage.setItem('cartItems', JSON.stringify(data));

Answer №2

Thank you so much for providing the solution, it worked flawlessly. I have included the corrected code below in case anyone else encounters a similar issue and needs some help.

const cartItems = JSON.parse(localStorage.getItem("cartItems")); 
   // console.log(cartItems);
    if(cartItems !== null){ 

        for(let i = 0; i<cartItems.length; i++){
        
            const tableRow = document.createElement("tr");
           
            const removeButton = document.createElement("button");
            removeButton.setAttribute("class", "btn btn-danger mt-1") ;
            removeButton.innerHTML = "remove";
            const tbody = document.getElementById("cartBody");
            tbody.appendChild(tableRow); 
            tableRow.appendChild(removeButton);
            /////////////////////// on click ///////////////////////         
            removeButton.addEventListener("click", function(){
                const parsedData = JSON.parse(localStorage.getItem('cartItems'));
                parsedData.splice(parsedData.indexOf(parsedData[i]), 1);
                localStorage.setItem('cartItems', JSON.stringify(parsedData));
            });           
        }
    }else{
        console.log("empty cart");
      
    }

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 could be causing the empty object return from the Async function in my Typescript code on Next JS?

Encountering issues with an async function. In the ../lib folder, I have a class for handling data from an API website. However, when attempting to load the API data within an async function, I encounter difficulties. The async function does not return a ...

Updating a JSON string in PHP by replacing any instances of double quotes

I'm looking to convert a JSON string into an array using PHP, but I'm having trouble escaping double quotes. $string = '["label":"Name","type":"text","placeholder":"Mario","name":"name",*], ["label":"Email","type":"email","placeholder":"< ...

Steps for adding a favicon to Content-Type: application/json

In my implementation using node.js, I have an API that returns a response with Content-Type: application/json. Here is an example: module.exports={ api: (req, res) => { let data = {"data": [1, 2, 3]}; res.status(200).json(d ...

What is the solution for resolving the "Duplicate key found" error in JSON-LD?

My Schema.org includes the following code for office hours, but it gives me an error when I test the URL using Google Structured Data Testing Tool. How can I resolve this error? Error: JSON-LD Duplicate key found. I have identified the issue: opens, c ...

Creating a personalized scrollball feature within a fancybox

Within my fancybox, I have a section with images that require a scroll bar. I currently have a scroll bar in place, but I am interested in implementing an anti-scroll (custom scrollbar) instead. I came across one option at https://github.com/Automattic/an ...

Hiding content and troubleshooting video playback problems in FancyBox

I'm facing an interesting issue. I've implemented FancyBox lightbox to showcase a "video" tag when users click on the image thumbnail, and it functions well with all varieties of HTML5 video. The challenge arises when testing in browsers older th ...

What are some tactics for avoiding movement in the presence of a border setting?

I created a webpage that has the following structure: .topbar-container { width: 100%; position: fixed; top: 0; background-color: #2d3e50; z-index: 999; display: flex; transition: height 500ms; } @media (min-width: 992px) { .topbar-cont ...

How can you personalize the dropdown button in dx-toolbar using DevExtreme?

Currently, I am working with the DevExtreme(v20.1.4) toolbar component within Angular(v8.2.14). However, when implementing a dx-toolbar and specifying locateInMenu="always" for the toolbar items, a dropdown button featuring the dx-icon-overflow i ...

leveraging Ajax to submit a segment of the webpage

-Modified- Greetings, I am facing a situation where I need to post only the second form on a page that contains two forms. The second form has a function for validating data such as date, email, etc. My goal is to send the second form without reloading ...

From Panda's Den to JSON Empire: Unraveling the Dataframe

After an exhaustive review and attempt at implementing all the other solutions on SO related to this challenge, I have yet to find a working solution. Question: How can I convert employee and supervisor pairs into a dynamic hierarchical JSON structure for ...

Creating a stand-alone NPM module for a Redux store to be used in a React application

Can the Redux Store be developed as a separate npm package for a React App and then imported into it? For instance: Assuming there is a fictional React Project named reactapp. A package called reactapp-reduxstore is created containing the Redux Store, al ...

What is the best way to extract data from a series of nested JSON objects and insert it into a text field for editing?

I am facing a challenge with appending a group of nested JSON objects to a text field without hard coding multiple fields. Although I have used the .map functionality before, I am struggling to make it work in this specific scenario. const [questions, setQ ...

Tips for guiding users to a different page based on whether a linkid is associated with a specific Cat

I created this script, but I am facing an issue with the redirect. Can someone please assist me as soon as possible? <?php include('config.php'); $number = intval($_POST['catid']); $query = mysql_query("SELECT * FROM sound ...

The values of variables persist even after refreshing the page

let quote; let author; // Establishing the Get Method for the Root Route in ExpressJS app.get('/', (req, res)=>{ res.render('home', { quote: quote, writer: author }); }); // Configuring the Post Method for t ...

I am trying to collapse the table header but I am having trouble doing so

@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100); @import url(https://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100); body { bac ...

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Inconsistent behavior of transform scale() between Chrome and Safari upon page refresh

My goal was to design a code that would adjust all content according to the browser size, ensuring that everything remains visible even when the window is resized. var docHeight = $(document).height(); var winHeight; var zoomRatio; function z(number) { ...

Having trouble sending the code through post message

I was trying to send some code to a node application using Postman with a POST message. In the body, I included the following code: module.exports = function() { var express = require('express'), app = express(); app.set('po ...

Struggling to parse an array of objects with dynamic keys in OPENJSON and SQL Server 2017?

I'm having issues parsing a collection of JSON documents in SQL Server 2017. Within one document, I've come across a nested array (shown below) that utilizes dynamic ObjectId's like '123' as the object Key instead of using a stati ...

Navigating through hidden input fields in Angular by utilizing the tab key

Seeking a method in Angular to navigate hidden inputs using tab functionality. I have several input forms that display only the text when not on focus. Is there a way to select an input and still be able to tab through the other hidden inputs? Any ideas o ...