Removing an article from a Vue.js localStorage array using its index position

I am facing an issue while trying to remove an item from localStorage. I have created a table to store all the added items, and I would like to delete a specific article either by its index or ideally by its unique id. Your assistance is greatly appreciated. Thank you in advance.

deleteOption(){
      this.test = JSON.parse(localStorage.getItem('test'))
      this.test.splice(index, 1)
},

test:[
   {
    id:1,
    item: test item 1
   },
   {
    id:2,
    item: test item 2
   },
   {
    id:3,
    item: test item 3
   },   
]


addItem () {

localStorage.setItem("test",JSON.stringify(this.test))

}


Answer №1

When using the getItem method in localstorage, it is important to remember that the returned value is a string and should be converted to an array before performing any operations:

  let data = JSON.parse(localStorage.getItem('data'));
  data.pop();

Answer №2

To address your situation, you should follow these steps:

  1. Retrieve the previously saved string from local storage
  2. Parse the string into an array
  3. Make necessary modifications to the array
  4. Convert the array back into a string
  5. Save the updated string back to local storage.

test:[
   {
    id:1,
    item: test item 1
   },
   {
    id:2,
    item: test item 2
   },
   {
    id:3,
    item: test item 3
   },   
]

localStorage.setItem("test",JSON.stringify(this.test))


function deleteByIndex(index)
{
  var arr = JSON.parse(localStorage.getItem('test'));
  arr = arr.splice(index, 1);
  localStorage.setItem("test",JSON.stringify(arr))
}

function deleteById(id)
{
  var arr = JSON.parse(localStorage.getItem('test'));
  arr = arr.filter(function(item) {
    return item.id !== id
   });
  localStorage.setItem("test",JSON.stringify(arr))
}

Answer №3

example = [
  {
    id: 1,
    item: "example item 1",
  },
  {
    id: 2,
    item: "example item 2",
  },
  {
    id: 3,
    item: "example item 3",
  },
];

newExample = example.filter((item) => item.id !== 2);

console.log(newExample);

This code snippet removes the item with id 2 from the array.

Answer №4

Could someone provide assistance as I am having difficulty retrieving the index of an object within an array stored in localStorage?

Answer №5

After multiple days of attempting, I am still unable to accomplish my goal. Despite following all the suggestions provided in this thread, one particular method ends up erasing all of my progress. It seems that whenever I try to add an option, all the options I had previously removed reappear.

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

Adjust the size of a div by clicking a button using Javascript

<script type="text/javascript"> var btn = document.getElementById("btn"); var panel = document.getElementById("panel"); var btn2 = document.getElementById("btn2"); function expandPanel() { btn.style.display="none"; panel.style="overflow:hidd ...

Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end. function findDateDifferences(obj1, ...

Extracting JSON Data into Text Boxes within jQuery UI Dialogs

Let me provide some context to my current issue. Due to the nature of the problem being work-related, I am unable to share much of the code. The task at hand involves working with a jQuery dialog. Essentially, I have a list of names displayed with a boots ...

Easily move a group of HTML elements at the same time with a simple

Exploring HTML5 Drag and Drop with Multiple Elements When it comes to dragging and dropping multiple elements in HTML5, there seems to be a limitation with the default draggable attribute. This attribute allows only one element to be dragged at a time, ma ...

Rendering real-time data using jQuery's Ajax functionality

Imagine having a webpage that gradually returns a large amount of data over time. Here's an example code snippet to illustrate this: <?php $iTime = time(); while(time()-$iTime < 10 ) { echo "Hello world"; echo str_repeat( ' &apos ...

The JSP page does not redirect after an Ajax post request has been made

When submitting a form with basic AJAX post, I am facing an issue where the redirection to the JSP does not occur upon success. Setting the redirect programmatically seems to create a new JSP instead of utilizing the existing one with POST data. After debu ...

Transforming React-Leaflet Popup into a custom component: A step-by-step guide

Currently working on a project where I am utilizing both React-Leaflet and Material-UI by callemall. The challenge I am facing involves trying to incorporate the Material-UI Card component within the <Popup></Popup> component of React-Leaflet. ...

Generate an array in JavaScript using the values from input fields

Is there a way to create a JavaScript array that stores the values of all input fields with the class 'agency_field', when there are x number of these fields in the form? I attempted to achieve this using jQuery, but encountered a syntax error. ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...

Adapting JavaScript functions from IE to work on Firefox and Chrome: A comprehensive guide

I have encountered an issue with a function that retrieves the selected text range within a contenteditable div. While it works perfectly fine in Internet Explorer, it doesn't seem to work in Firefox and Chrome. Could someone kindly provide guidance ...

What is the best way to implement a fadeout or timeout for success and warning alerts in OpenCart 2.2?

Is there a way to set a timeout for alert boxes in Opencart 2.2 so that they disappear after a few seconds? I've tried the code below, but it didn't work out. Alternatively, is it possible to make the popup disappear when clicking anywhere on the ...

Facing an issue with webpack-dev-server where it displays a blank screen

Hello! I am currently in the process of creating my first MERN stack application, using Webpack as the build tool. The main objective is to have Express serving the APIs for the app and webpack-dev-server handling the static content (from my static directo ...

Which comes first in AngularJS: ng-include or ng-repeat?

What is the outcome if I have a template containing ng-repeat and include it using ng-include? Will the included template have the completed ng-repeat, or will it be included without the ng-repeat being complete (and then completed after inclusion)? ...

What is the best way to remove text using javascript?

Hey everyone! I am new to coding in javascript and I'm hoping for some help with stripping text. I have a string that is formatted like this: <iframe src="http://embed.videokoo.com/61YVek?client_file_id=390856&width=720&height=480" style=" ...

Verification upon button press for a form

Currently, I have a form with multiple textboxes that are being validated using the Required Field Validator. However, there is also a captcha control that is not getting validated. I can validate it using JavaScript though. At the moment, an alert pops u ...

Create a webpage in full screen mode with a video player that fills the entire screen

Here is the HTML code I am working with: <div id="container"> <video id="video" src="video.ogv" loop></video> </div> The "container" div and video element occupy the entire screen. #container { po ...

efforts to activate a "click" with the enter key are unsuccessful

I'm attempting to enhance user experience on my site by triggering the onclick event of a button when the enter key is pressed. I've tried various methods below, but all seem to have the same issue. Here is my HTML (using Pug): input#userIntere ...

Is there a way to confirm if all div elements have a designated background color?

I have a scenario where I have dynamically added several divs with a specific class to my webpage. These divs change color when the user hovers over them. I am trying to trigger a specific function once the last div has been set to a particular backgroun ...

The execution of my code differs between running it locally and in online code editors like CodePen or Plunker

Using jQuery Terminal, I have the following code: function display() { for (var i = 0; i < 100; ++i) { this.echo('line ' + i, { flush: false }); } this.flush(); setTimeout(function() { //thi ...

Interpolating strings in a graphQL query

Exploring the world of Gatsby and its graphQL query system for asset retrieval is a fascinating journey. I have successfully implemented a component called Image that fetches and displays images. However, I am facing a challenge in customizing the name of ...