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

Explore numerous databases using mongoosastic

Currently in my Node.js application, I am utilizing Mongoosastic to fetch data from ElasticSearch : Article.search({ "match_all": {} }, function (err, results) { console.log(results.hits.hits); Post.search({ "match_all": {} }, function (err, r ...

The Material-UI Select component does not reflect changes after an onChange event

I've encountered this issue all over the internet, but no explanation seems to resolve it for me. Using Material-UI Select and traditional setState(...) in React (not using hooks). The core of my component is as follows: class MyComponent extends Co ...

How do I fix the build error that says "Operator '+' cannot be used with types 'number[]'?

The function below is designed to generate unique uuidv4 strings. function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => ( c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)) ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...

Efficiently uploading multiple files using AJAX in conjunction with Codeigniter

Greetings! I'm attempting to utilize ajax and codeigniter to upload multiple images. As a beginner in ajax and jquery, I would greatly appreciate any assistance in identifying where I might be going wrong or missing something. Below is my controller ...

Why isn't setInterval set to a duration of one thousand milliseconds?

While trying to use some code from w3schools, I noticed that the setInterval in the example is set to 5 instead of 5000. Shouldn't it be in milliseconds? If not, how can I speed up this animation? When I try reducing it to decimals like 0.01, the anim ...

The android application experiences crashing issues when utilizing the position or zIndex style properties within a react-native environment

In my code, I am attempting to display a semi-transparent black screen over my page in order to show a message or prompt in the center. I have tried using zIndex or elevation with position:'fixed' or position:'obsolet', and it works per ...

The filter function in JavaScript's Array is malfunctioning on Internet Explorer version 7

My web application includes a jQuery plugin that is functioning correctly in Internet Explorer 10 and 11. However, it is not working in IE 7. Upon investigation, I discovered that the value of the filter method is showing as undefined. The line of code th ...

Restricting the amount of requests per user within a single hour [Node.js]

As I work on developing a server side application using Nodejs and Express, one thing that crosses my mind is limiting the number of requests per user within a specific time frame to prevent malicious hackers from overwhelming the server with spam. I&apos ...

Retrieving the value of a specific property nested within a JSON object using basic JavaScript

Hey there! Thanks for taking the time to check out my question. I'm diving into JavaScript and I've hit a roadblock trying to solve this particular problem: I'm looking to extract the value of a property nested within a JSON object under a ...

What is the proper method for implementing a scrollable effect to the <v-bottom-sheet> element within the Vuetify framework?

Within my Vue.js project, I am utilizing the v-bottom-sheet component from Vuetify framework (version 2.1.12). Upon reviewing my code, you can observe that the v-card is enclosed within the v-bottom-sheet. The issue arises with the scrollable parameter of ...

Are there any methods for simultaneously hosting both React and vanilla JavaScript websites?

I want to host a full-fledged web application that is primarily implementing ReactJS, but also contains sections utilizing vanilla JavaScript. Is it possible to host a web app that combines both React and vanilla JavaScript functionalities? (My backend i ...

A guide to accessing a property value in Angular 6 from an object using a string key

In my Angular application, I am receiving an object with multiple arrays from a REST service. I need to access the value from the incoming object based on the property name. Here is what the object looks like: data{ array1:{}, array2:{}, array3:{} } Th ...

Execute a single test from a particular test suite using Jest

Within my file named "test-file-1", I have several describes (test suites) with distinct names, each containing tests that may share similar names across different test suites. In order to run a single test suite or test, I enter the following command: n ...

Node.js Export Module Error - importance of separating concerns

I have been attempting to implement separation of concerns by using export module. Everything functions properly when used without separating concerns, but as soon as I try to import generateUrlArray() from const db = require('../db'), nothing se ...

"Encountering a 405 error when transmitting information from an HTML file to a Python Flask server using 'GET / HTTP/1.1'

As someone who is brand new to the world of python and AJAX, I have been piecing everything together from various sources online including examples and Flask documentation. So far, I have managed to make some progress. My goal is to send latitude and longi ...

Unable to access MongoDB documents using NodeJS/Express

I can't seem to figure out why I am not receiving any results from a GET call I am testing with Postman. Let's take a look at my server.js file: const express = require("express"); const mongoose = require("mongoose"); const ...

Deleting multiple subdocuments and their related subdocuments with Mongoose

In my application, I have a Project document that contains an array of subdocuments structured as Tasks. Each Task has its own array of subdocuments with a schema called Comments. const projectSchema = new Schema({ _id: Schema.Types.ObjectId, name: { ...

Creating form components in a row

I'm currently working on an app and I'm attempting to align 3 form elements in a ratio of 25/25/50, but it's proving to be quite challenging. At the end of this message, you'll find a picture showing the current layout. Additionally, I& ...

BlendModeGlobal operations

Experimenting with the globalCompositeOperation property in a loop by passing different strings (source-atop, source-over, etc.) to the same 2D context, I observed that Firefox only allowed me to draw a few shapes while Opera only displayed the last one. ...