Darrow Hartman
Darrow Hartman

Reputation: 4383

Using localStorage/sessionStorage to store arrays

I am trying to save an array inside of a localStorage value. I can only access chars of the value, not the grouped value. I have been trying to write a function to group them by commas, but I can't figure out how to do it correctly.

// setting values
localStorage.setItem("foo", [15,"bye"]);

// writes the whole thing.
document.write(localStorage.getItem("foo")); // returns 15,bye

// only writes the first character, instead of one part of the array 
// (in this case it would be 15).
document.write(localStorage.getItem("foo")[0]); // returns 1

Upvotes: 2

Views: 853

Answers (3)

Prashant Pimpale
Prashant Pimpale

Reputation: 10697

I would use JSON.stringify to set the data and JSON.parse to fetch the stored data.

Try this:

localStorage.setItem("foo", JSON.stringify([15,"bye"]));

// writes the whole thing.
localStorage.getItem("foo"); // returns 15,bye

var data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])

Upvotes: 2

Code Maniac
Code Maniac

Reputation: 37755

You can parse json

let data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])

Or you can split by ',' and get the 0th index item.

localStorage.getItem('foo').split(',')[0]

Upvotes: 0

brk
brk

Reputation: 50291

localStorage can only store string in its value, that is why it is storing only 15;

Use JSON.stringify and store it in the local storage as localStorage.setItem("foo",JSON.stringify([15,"bye"]));

If you want to retrieve the value do as JSON.parse(localStorage.getItem("foo"));

Upvotes: 1

Related Questions