Looping Through Localstorage in HTML5 and JavaScript

Looping through localStorage in HTML5 and JavaScript

You can use the key method. localStorage.key(index) returns the indexth 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



Leave a reply



Submit