2

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
Darrow Hartman
  • 4,142
  • 2
  • 17
  • 36

3 Answers3

2

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])
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
1

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"));

brk
  • 48,835
  • 10
  • 56
  • 78
0

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]
Code Maniac
  • 37,143
  • 5
  • 39
  • 60