Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update a specific value from the array in local storage?

There is an array of strings in the local storage. I want to find a specific value from that array, and update only that specific value without changing the rest of the array.

function saveLocalChecked(task) {
    let tasks = JSON.parse(localStorage.getItem('tasks'));
    const taskIndex = task.children[1].innerText;

    for(let i = 0; i < tasks.length; i++) {
        if(tasks[i] === taskIndex) {
            localStorage.setItem('tasks', JSON.stringify(tasks[i] + '*'));
        }
    }
}

So, in this function, I create the tasks array by pulling the items from the local storage. In the for loop, I loop over the tasks array to find a specific element. And now, I want to update that element by concatenating the asterisk sign. But after checking my local storage, there is only that updated element, and the rest of the array just disappeared.

How to fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That is because you are replacing the entire storage for that specific array with the one single element you apply the change to. Change the item you want within your if condition and send the entire array, with the updated element, back to storage

function saveLocalChecked(task) {
    let tasks = JSON.parse(localStorage.getItem('tasks'));
    const taskIndex = task.children[1].innerText;

    for(let i = 0; i < tasks.length; i++) {
        if(tasks[i] === taskIndex) {
            tasks[i] = tasks[i] + '*'
            localStorage.setItem('tasks', JSON.stringify(tasks));
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading