Tima Donbragoni
Tima Donbragoni

Reputation: 43

Set localstorage for array of elements in javascript

I need to set an array of objects values to localstorage using vanilla JavaScript.

I have tried looping through the array and getting each index then setting each index it doesn't seem to work. However if i single reference each element it works, which is strange...

const theme_cache = [document.getElementById('panel').style.background,document.getElementsByClassName('icon-bar')[0].style.color]

     const saved_theme_cache = JSON.parse(localStorage.getItem('cached-elements'));

    element.onchange = function(){
         localStorage.setItem('cached-elements', JSON.stringify(theme_cache));
    }   

Upvotes: 1

Views: 73

Answers (1)

Jonathan Hamel
Jonathan Hamel

Reputation: 1393

localStorage is a key/value pair and accepts only strings as value parameters. When passed something else, it will call it's toString() representation. You should use JSON.stringify and JSON.parse to serialize/deserialize the value.

const listOfTests = [{test: "test"}]
localStorage.setItem("tests", JSON.stringify(listOfTests));

const listOfTestsFromLocalStorage = JSON.parse(localStorage.getItem("tests"))

Upvotes: 3

Related Questions