1

I have a array stored in localStorage that has a key named "key" it contains this values ["Gio","Ben"]

how do i get the length I've tried

localStorage.getItem("name").length;

but it shows a different output what i was expecting was supposed to be 2.

Thanks in advance

Yatoooo
  • 13
  • 1
  • 3

4 Answers4

4

You have to parse the array using JSON.parse and then you can get its length just like any other array.

var arrayFromStroage = JSON.parse(localStorage.getItem("name"));
var arrayLength = arrayFromStroage.length;

Just for your awareness, localStorage.getItem("name").length; will get you the length of JSON string that you have stored in localStorage. For array ["Gio","Ben"], its JSON string is "["Gio","Ben"]". So the length would be 13.

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • Thanks it worked, but how about if i wanna get a specific value from the array? – Yatoooo Apr 18 '18 at 07:08
  • @Yatoooo Then you can iterate over the parsed array, i.e. `arrayFromStroage` in my snippet. Or, you could even filter over that array. – Nisarg Shah Apr 18 '18 at 07:10
  • Thanks for the help. – Yatoooo Apr 18 '18 at 07:12
  • sir how do i loop print the contents of the array I've tried for(var i = 0; i < arrayLength; i++){ //print } but it prints only the last value of the array which is Ben – Yatoooo Apr 18 '18 at 07:19
  • @Yatoooo There are several ways of doing that. First being `for(var i = 0; i < arrayLength; i++){ console.log(arrayFromStroage[i]); }` Second is, `arrayFromStorage.forEach(t => console.log(t));` You should refer [this](https://stackoverflow.com/q/3010840/5894241) question for more information. – Nisarg Shah Apr 18 '18 at 07:35
1

The localStorage only stores Strings.

If you have an Array in there, you need to parse it before using it with JSON.parse :

var arrStr = '["Gio","Ben"]';

console.log(JSON.parse(arrStr));
Zenoo
  • 12,670
  • 4
  • 45
  • 69
0

Actually we can only save string value in local Storage. the getItem("name") function return a string. so first you have to convert this into a json object and then you can get array length.

JSON.parse(localStorage.getItem("name")).length;
Faraz Babakhel
  • 654
  • 5
  • 14
0

Actually we have string value in local Storage. the getItem("name").length function return total number of characters in a string. So, in case of Lists you can try all of the above mentioned tricks but in case of dictionary they won't work. So, what u can do is just fetch all the keys and then count them. Here is what you can do:

Object.keys(name).length;

it will work.

Leo Zhao
  • 544
  • 7
  • 18