简体   繁体   中英

How to remove an object from an array in local storage

I am trying to remove a note from local storage by identifying its title. I checked w3schools and this forum for info. I am able to save the array but, I can't remove a specific note.

I tried, no change, an example of what I am trying to achieve,

This is my local storage before removing:

[{title: "Laundry", content: "Fold Clothes"}, {title: "Cook", content: "Buy Food"}, {title: "Read", content: "Go to the library"}] 0: {title: "Laundry", content: "Fold Clothes"} 1: {title: "Cook", content: "Buy Food"} 2: {title: "Read", content: "Go to the library"}

My desired output after removing:

[{title: "Laundry", content: "Fold Clothes"}, {title: "Cook", content: "Buy Food"}] 0: {title: "Laundry", content: "Fold Clothes"} 1: {title: "Cook", content: "Buy Food"}

I want to be able to remove an item based on its title Read

const editNote = (e) => {
    saveContent.addEventListener('click', (e) => {
        e.preventDefault()
    
        let notes = []
        let note = {
            title: noteTitle.value,
            content: noteContent.value
        }

        // Parse the serialized data back into an aray of objects
        notes = JSON.parse(localStorage.getItem('items')) || [];
        // Push the new data (whether it be an object or anything else) onto the array
        notes.push(note);
       
        // Re-serialize the array back into a string and store it in localStorage
        localStorage.setItem('items', JSON.stringify(notes));
        // input.textContent = note.title 
    
        //remove notes by id
        const removeNote = () => {
            let title = noteTitle
            const index = notes.findIndex((note) => note.title === title)
    
            if (index > -1) {
                notes.splice(index,1);
            }
        }

        delNote.addEventListener('click', (e) => {
            removeNote()
            e.preventDefault()  

            // window.location.href='index.html'

        })

    })  

    
}

editNote()

You need to set item into local storage after you update your data

const removeNote = () => {
        let title = noteTitle
        const index = notes.findIndex((note) => note.title === title)
    
        if (index > -1) {
            notes.splice(index,1);
            localStorage.setItem('items', JSON.stringify(notes))
        }
    }
localStorage.removeItem('ITEM TO REMOVE');

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Storage/removeItem

I eventually figured it out. Thank you all for replying and providing guidelines.

 let input = document.querySelector('.input-bar') let addItem = document.querySelector('.submit-btn') let clearAll = document.querySelector('.clear-btn') // pay attension to indentation and ele location it will determine success addItem.addEventListener('click', (e) => { e.preventDefault() // Parse the serialized data back into an aray of objects items = JSON.parse(localStorage.getItem('items')) || []; // Push the new data (whether it be an object or anything else) onto the array items.push(input.value); item = input.value // Re-serialize the array back into a string and store it in localStorage localStorage.setItem('items', JSON.stringify(items)); var clear = document.createElement('button') clear.innerHTML= '<i class="fa fa-trash" style="font-size:20px;color: #ac2412"></i>' let itemsEl = document.getElementById('items') let para = document.createElement("P"); var t = document.createTextNode(`${input.value}`); para.appendChild(t); para.appendChild(clear) itemsEl.appendChild(para); input.value = '' clear.addEventListener('click', (e) => { itemsEl.removeChild(para) e.preventDefault() for (let index = 0; index < items.length; index++) { if (items[index] === para.textContent) { items.splice(index, 1) localStorage.setItem('items', JSON.stringify(items)); } } }) }) clearAll.addEventListener('click', (e) => { document.getElementById('items').innerHTML = '' localStorage.clear() })
 * { box-sizing: border-box; margin: 0; padding: 0; } body { color: white; background-color: black; margin: 40px 0px; text-align: center; } input { width: 300px; height: 46px; outline: none; background: transparent; border-color: silver; border-radius: 0; color: var(--mainWhite); font-size: 1.7rem; } h1 { margin: 20px 0px; }.submit-btn { margin: 0px 5px; width: 50px; height: 50px; outline: none; /* color: white; */ background-color: rgb(21, 96, 194); color: white; font-size: 1.7rem; }.items-list { list-style-type: none; } li { display: inline-flex; border: 1px solid slategrey; font-size: 22px; margin: 20px 0px 0px 0px; } button { outline: none; margin: 0px 0px 0px 200px; }.clear-btn { width: 100px; height: 40px; margin: 30px; outline: none; background-color: rgb(21, 96, 194); color: white; font-size: 20px; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="style:css"> <script src="https.//code.jquery.com/jquery-3.2.1.slim.min:js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https.//cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min:js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https.//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min:js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <link rel="stylesheet" href="https.//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <title>Groceries</title> </head> <body> <h1>Grocery List</h1> <div> <input class="input-bar" type="text"> <span> <button class="submit-btn"> <i class="fa fa-pencil" aria-hidden="true"></i> </button> </span> <ul class="items-list" id="items"></ul> </div> <button class="clear-btn">Clear</button> <script src="index.js"></script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM