How to recover an array saved on localStorage

Asked

Viewed 462 times

5

var pessoa = ["Bonito","Alto","Magro"];
Window.localStorage.setItem('pessoa',JSON.stringify(pessoa))

pessoa=[null]

Now I want to recover that value Bonito,Alto,Magro one by one , which is no longer in the variable but in the localstorage in that variable below

var pessoaAntiga = 

2 answers

10

You need to parse your string for JSON:

pessoaAntiga = JSON.parse(window.localStorage.getItem('pessoa'))

4

I don’t know if it was a typo here, but the object window that’s all lower case (you capitalized the "W", which will result in error).

You don’t need to use JSON parse, just put it on localStorage the direct array it is already saved in string form.

That is, when using:

var pessoa = ["Bonito","Alto","Magro"];
window.localStorage.setItem('pessoa', pessoa);

The value of localStorage will be the array in string form:

"Bonito","Alto","Magro"

And to recover you use .getItem() and .split(",") to convert to array again (if there is no comma in the middle of the words in the array):

var pessoaAntiga = window.localStorage.getItem('pessoa').split(",");
  • 5

    This method should be used carefully, if any string in the array contains comma, the split will not return the expected value. And just to be explicit, it is not that Window be wrong, but Window refers to the type (constructor function), equator window the value (object)

  • True friend. I will reevaluate the answer. Obg!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.