Home > Software engineering >  JS LocalStorage - Why am i getting extra values with for in loop
JS LocalStorage - Why am i getting extra values with for in loop

Time:12-19

i am trying to make a basic notes app using js a i have stored notes in local storage and i am trying to print those note using for in loop everything is fine but i dont know why am i getting extra values like length, getItem, key etc can anyone help

my code

(function () {
for (key in localStorage) {
    let notes = document.getElementById("notes")
    let value = localStorage.getItem(key)
    notes.innerHTML = notes.innerHTML   `${key}: ${value} <br>`
}
})();

CodePudding user response:

localStorage (and likewise sessionStorage) is an object similar to Map, in that its own properties and methods don’t directly correspond to values actually kept in the storage. Enumerating its properties and accessing missing properties on it will fall back to returning items from the underlying storage, but that is actually a design flaw that is best not relied on.

To enumerate the contents of a storage object (localStorage or sessionStorage), you shouldn’t use for-in, Object.keys or Object.entries. Use key, length and getItem:

function* storageEntries(storage) {
    for (let i = 0; i < storage.length;   i) {
        const key = storage.key(i); 
        yield [key, storage.getItem(key)];
    }
}

for (const [key, val] of storageEntries(localStorage)) {
    console.info(
        `localStorage ${JSON.stringify(key)} maps to ${JSON.stringify(val)}`);
}

Using the for-in loop and property accesses will return properties of the localStorage object itself, while using Object.entries or Object.keys will skip them even if there actually are storage items with the same keys. For example:

localStorage.clear();
localStorage.setItem('length', -69420);
localStorage.setItem('getItem', 'where is your god now?');

// returns wrong values
const result0 = [];
for (var key in localStorage) {
    result0.push(key, localStorage[key]);
}
console.log('WRONG:', result0);

// returns right values, but also spurious keys
const result1 = [];
for (var key in localStorage) {
    result1.push(key, localStorage.getItem(key));
}
console.log('WRONG:', result1);

// returns an empty array
console.log('WRONG:', Object.entries(localStorage));

// returns two key-value pairs
console.log('RIGHT:', Array.from(storageEntries(localStorage)));

CodePudding user response:

localStorage contains key/value pairs similar to a JS object with some built in functions such as setItem and getItem. In order to iterate over everything in localStorage you would have to do it the same way you would with a JS object. Here is one way to do it.

 for (const [key, value] of Object.entries(localStorage)) {
   console.log(key, value);
 }

This would log the keys and values of each item saved in the localStorage

CodePudding user response:

localStorage is an object with properties and methods. You're looping over all of these items you're performing the for of loop. Try just reaching in for the actual values with Object.keys(localStorage).forEach(item => {...}) or Object.entries(localStorage).forEach(([key, value]) => {...})

  • Related