How to delete a specific item/object in localStorage?
All the answers were right but you have to :
- Parse the string in localStorage to JSON (you did that)
- Remove the item you don't want (with slice() )
- Make the JSON to string
- Re-set it in the localStorage
So :
1.
var items = JSON.parse(localStorage.getItem("items")); // updated
2.
for (var i =0; i< items.length; i++) {
var items = JSON.parse(items[i]);
if (items.itemId == 3) {
items.splice(i, 1);
}
}
3.
items = JSON.stringify(items); //Restoring object left into items again
4.
localStorage.setItem("items", items);
Parsing to JSON and storing it as string is kinda annoying, but that's the way localStorage works.
Remove a specific item from localstorage with js
Here is refactored code.
Firstly there is no need to store count, as we always have access to names.length
Store only names on localStorage, not entire HTML
- For add and remove a name, fetch names array from localStorage, update it and save it back to localStorage.
- After every action just update the UI using a single function call.
Note: Renamed names-field
to name-field
in the below implementation.
Here is the working code: https://jsbin.com/simitumadu/1/edit?html,js,output
var $list = document.getElementById('list');var $resetMessage = document.getElementById('reset-message');var $resetCouter = document.getElementById('record-counter');
var names = getNames();
if(names == null){ setNames([]); // initializing the empty array for first time.}
renderData(); // display data
function addNameRecord() { $resetMessage.innerHTML = ''; var name = document.getElementById('name-field'); addName(name.value); renderData(); name.value = ''; //clear input field}
function renderData(){ var names = getNames(); $resetCouter.innerText = names.length; // Count var namesListHTML = ''; names.forEach(function(name, index){ namesListHTML = namesListHTML + '<p class="name-entry"><strong>' + (index + 1) + '. </strong> ' + name + '</p><button onclick="clearThisItem(\'' + name + '\')">Remove</button>' }); $list.innerHTML = namesListHTML;}
function clearArray() { setNames([]); // clear names $resetMessage.innerHTML = 'Array has been purged.'; renderData();}
function clearThisItem(name){ removeName(name); // remove from localStorage renderData();}
function getNames(){ namesStr = localStorage.getItem('names'); if(namesStr) { return JSON.parse(namesStr); } return null;}
function setNames(names){ return localStorage.setItem('names', JSON.stringify(names));}
function addName(name){ var names = getNames(); names.push(name); setNames(names);}
function removeName(name){ var names = getNames(); var index = names.indexOf(name); if (index > -1) { names.splice(index, 1); } setNames(names);}
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title></head><body> <p>Count : <span id="record-counter"></div></p> <input id="name-field"> <button onclick="addNameRecord()">Add</button> <button onclick="clearArray()">Clear</button> <div id="list"></div> <div id="reset-message"></div> </body></html>
How can i delete specific item from LocalStorage
Try to use localStorage.removeItem('ITEM_NAME')
method of the localStorage
object.
Here is an example of creation, getting and removing items in the localStorage
localStorage.setItem('aaa','1231') //undefined
localStorage.getItem('aaa') //"1231"
localStorage.removeItem('aaa') //undefined
localStorage.getItem('aaa') //null
Here is example of code for your case:
function displayComment(comment) {
var html = $(`<div class="card" data-id="${comment.id}"><h5>${comment.card}</h5></div>`);
$('.yorum').append(html);
$('.yorum').find(html).click(function () {
$(html).remove();
var arr = JSON.parse(localStorage.getItem('todo'));
for(var i=0;i<arr.length;i++)
{
if(arr[i].id=this.getAttribute('data-id'))
{
arr.splice(i,1);
break;
}
}
localStorage.setItem('todo', JSON.stringify(arr));
});
}
How to remove the item from the local storage by clicking on div?
You Can Use : localStorage.removeItem('object');
to remove object saved as object
.
window.localStorage
Supports mainly 5 methods:
localStorage.setItem('key', 'value'):
/* Add key and value to localStorage */
localStorage.getItem('key') // returns 'val'
/* Retrieve a value by the key from localStorage */
localStorage.removeItem('key')
/* Remove an item by key from localStorage */
localStorage.clear()
/* Clear all localStorage */
localStorage.key(index) //retrun key
/* Passed a number to retrieve nth key of a localStorage */
Delete specific element in the array in localstorage using javascript and React
You can use these 2 functions to Get and Remove Items from Local Storage.
const getElementsfromLocalStorage = () => {
let elements = [];
if (localStorage.getItem('reptiles')) {
elements = JSON.parse(localStorage.getItem('reptiles'));
}
return elements;
};
const removeElementLocalStorage = (name) => {
let elements = getElementsfromLocalStorage();
elements = elements.filter(element => element.name !== name);
localStorage.setItem('reptiles', JSON.stringify(elements));
};
Now, when you are rendering the list, render a button with every list item and call the function removeElementLocalStorage
when the button is clicked with the value.
<li>
<span>{reptile}</span>
<button onClick={() =>removeElementLocalStorage(element.name)}>Remove</button>
</li>
Related Topics
Mobile Safari Sometimes Does Not Trigger the Click Event
Javascript: How to Redirect a Page After Validation
Stop Just One Dropdown Toggle from Closing on Click
React-Native React-Navigation Undefined Is Not an Object (Evaluating 'S.Value.Startswith')
How to Modify Chartjs Tooltip So I Can Add Customized Strings in Tooltips
Useselector Not Updating When Store Has Changed in Reducer. Reactjs Redux
How to Format and Display Json Data Using Array.Map in Reactjs
Django Template JavaScript Passing a Python Variable to a JavaScript One
Typescript - Possible to Disable Type Checking
How to Build Pdf File from Binary String Returned from a Web-Service Using JavaScript
Sort Json Data Based on Date and Time
How to Instantiate a File Object in JavaScript
Use Lodash to Find Objects in an Array Matches an Id (Complex, Drilldown)
How to Sort Data in Ascending or Descending Order in Reactjs
Remove Everything After Last Backslash
Trigger JavaScript Event If Div Innertext Change
Bootstrap Button Drop-Down Inside Responsive Table Not Visible Because of Scroll