Looping through localStorage in HTML5 and JavaScript
To iterate over localStorage
using for
loop and access key-value pairs using .key()
and .getItem()
methods:
This operation logs each key-value pair demonstrating direct enumeration and retrieval.
Non-stringy business: dealing with non-string data
localStorage
is built for storing string values. Storing arrays or objects requires serialization using JSON.stringify
and deserialization using JSON.parse
:
Not all browsers fully support the structured clone algorithm for non-string data, hence the JSON twist.
Iterating the lot: useful patterns and common pitfalls
No, no, no to for...in!
Despite for...in
appearing attractive for iterations, not advisable for localStorage
. It's designed for general objects, not Storage objects, and could get you into a thick soup.
Keys, please! Using Object.keys()
To get all keys from localStorage
, use Object.keys()
. It returns an array, enabling use of array methods like .forEach()
, .map()
, and .filter()
:
Pair them up with Object.entries()
Object.entries()
provides an array of key-value pairs for direct iteration:
jQuery's looping
If jQuery is your weapon of choice, $.each
is your armour:
Chrome's local speciality
Chrome has a local flavour allowing for direct iteration over localStorage
objects without needing .key()
:
Dealing with the quirky and special cases
Saving the order: Arrays to the rescue!
To guarantee order, serialize an array instead of individual items. Arrays never forget their order (unless you scramble them):
Are we compatible? Browser check!
Check browser compatibility for localStorage
and serialization methods in case of older browsers or restrictive settings:
The important stuff: Storing complex data
Shy away from splitting a single string for storage. Instead, smartly use structured data with unique keys for efficient access. Be cautious with quota limits (typically 5MB) and take note of browser policies that could mess with your merry storage plans.
Was this article helpful?