Looping through localStorage in HTML5 and JavaScript
You can use the key
method. localStorage.key(index)
returns the index
th key (the order is implementation-defined but constant until you add or remove keys).
for (var i = 0; i < localStorage.length; i++){
$('body').append(localStorage.getItem(localStorage.key(i)));
}
If the order matters, you could store a JSON-serialized array:
localStorage.setItem("words", JSON.stringify(["Lorem", "Ipsum", "Dolor"]));
The draft spec claims that any object that supports structured clone can be a value. But this doesn't seem to be supported yet.
EDIT: To load the array, add to it, then store:
var words = JSON.parse(localStorage.getItem("words"));
words.push("hello");
localStorage.setItem("words", JSON.stringify(words));
How to loop through localStorage values
Try using Object.keys(localStorage)
. As you requested a key:
var arrayOfKeys = Object.keys(localStorage);
Easy as that! That returns an array of keys. Now, if you want the values:
var arrayOfValues = Object.values(localStorage);
It returns an array.
Note that Object.values
is experimental, so an alternative would be:
var arrayOfValues = [];
for(var i in localStorage){
if(localStorage.hasOwnProperty(i)){
arrayOfValues.push(localStorage[i]);
}
}
How to filter a loop through local storage
This is a simple implementation that I think might help you.
async function fetchMovie(movieTitle) {
const apiUrl = `http://www.omdbapi.com/?t=${movieTitle}&plot=full&apikey=836f8b0`;
let res = await fetch(apiUrl);
res = await res.json();
const title = res.Title;
saveSearch(title); // Should only pass the string:title
}
fetchMovie('spiderman');
function saveSearch(title) {
if (!localStorage.getItem('movies')) localStorage.setItem('movies', ''); // Initialize the localStorage
// e.g: (In localStorage)
// Avenger,Spiderman,The Antman etc..
// return this string & convert into an array
let movies = localStorage
.getItem('movies')
.split(',')
.filter((n) => n);
// Check if the title is already exists
if (!movies.includes(title)) {
movies.push(title);
}
// Also store in localStorage as a string seperated by commas (,)
movies = movies.join(',');
localStorage.setItem('movies', movies);
}
Loop & search through ALL items in localStorage
Problem now SOLVED. The issue was that each time data was saved to localStorage, one extra empty item was stored at the bottom of the local db as a consequence of an incorrectly written for loop (in the setItem part.) arrayIndex < guestData.length should have been arrayIndex < guestData.length-1. arrayIndex < guestData.length-1 stores all items without creating an empty item at the bottom of the database which later messed up the search algorithm, as the last value to be search was undefined (the empty item).
How do I use a for loop with localStorage to remove an item?
localStorage is an object, you can loop through it like this
localStorage.setItem("order", 1);
for (var attr in localStorage){
if (attr == 'order') {
alert(localStorage[attr]);
localStorage.removeItem(attr);
}
}
Though there is no reason to loop, as you can simply call
localStorage.removeItem('order');
if you already know the key's name!
Related Topics
Difference Between HTMLcollection, Nodelists, and Arrays of Objects
Calling a JavaScript Function Returned from an Ajax Response
Add/Delete Table Rows Dynamically Using JavaScript
How to Use JavaScript to Change the Form Action
HTML - Attributes VS Properties
Does the Onchange Event Propagate
Formdata.Append("Key", "Value") Is Not Working
How to Add Custom HTML Attributes in Jsx
Jquery's .Click - Pass Parameters to User Function
Upload File with Ajax Xmlhttprequest
Input Type=File Show Only Button
Check a Radio Button with JavaScript
How to Format/Tidy/Beautify in JavaScript
How to Remove the "No File Chosen" Tooltip from a File Input in Chrome