Как удалить объект из массива в локальном хранилище - PullRequest
0 голосов
/ 06 августа 2020

Я пытаюсь удалить заметку из локального хранилища, указав ее заголовок. Я проверил w3schools и этот форум для получения информации. Я могу сохранить массив, но не могу удалить специфику c примечание.

Я пробовал, без изменений, пример того, чего я пытаюсь достичь,

Это - это мое локальное хранилище перед удалением:

[{title: "Laun dry", content: "Fold Clothes"}, {title: "Cook", content: "Buy Food"}, {title: "Читать", содержание: "Go в библиотеку"}] 0: {title: "Laun dry", content: "Fold Clothes"} 1: {title: "Cook", content: "Buy Food" } 2: {title: "Прочитать", содержание: "Go в библиотеку"}

Мой желаемый результат после удаления:

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

Я хочу иметь возможность удалять элемент на основе его названия Прочитать

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()

Ответы [ 3 ]

1 голос
/ 06 августа 2020

Вам необходимо поместить элемент в локальное хранилище после обновления данных

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))
        }
    }
0 голосов
/ 10 августа 2020

Я в конце концов разобрался. Спасибо всем за ответы и рекомендации.

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>
0 голосов
/ 06 августа 2020
localStorage.removeItem('ITEM TO REMOVE');

Ссылка: https://developer.mozilla.org/en-US/docs/Web/API/Storage/removeItem

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...