sessionStorage into array and print all values in the array
Asked Answered
C

3

10

I am currently trying to store an array into sessionStorage and then retrieve the data from sessionStorage. Then, store the sessionStorage data back into an array.

var testArray = ["Shirt", "Bottom", "Shoes"];
window.sessionStorage.setItem("items", JSON.stringify(testArray));
var storedArray = JSON.parse('[' + sessionStorage.getItem("items") + ']');
var i;
for (i = 0; i < storedArray.length; i++) {
     alert(storedArray[i]);
}

Am I doing anything wrong here?

Cachinnate answered 28/6, 2016 at 18:2 Comment(1)
JSON.parse(sessionStorage.getItem("items"));.. What made you concatenate [ \ ] there.. ?Alexina
R
24

It is already stored as an array, you don't need the brackets. What you are doing is putting the original array in a new array.

try this:

var testArray = ["Shirt", "Bottom", "Shoes"];
window.sessionStorage.setItem("items", JSON.stringify(testArray));
var storedArray = JSON.parse(sessionStorage.getItem("items"));//no brackets
var i;
for (i = 0; i < storedArray.length; i++) {
             alert(storedArray[i]);
}

https://jsfiddle.net/517x5rcg/

Rubierubiginous answered 28/6, 2016 at 18:5 Comment(1)
You are amazing! Thank you so much. I had no idea about the JSON.parse function! :DPurposeful
N
2

You don't need to wrap the array with []. sessionStorage.getItem("items") returns the JSON stringified array, you are wrapping the array with another array. Your problem is the alert function that converts the array into a string (just like joined array elements by calling the Array.prototype.join method), this is because alert can only show strings. This probably makes you think that there is no array. Use console.log for debugging.

Nisbet answered 28/6, 2016 at 18:7 Comment(0)
C
0

    let testArray = ["one", "two", "three"];
    sessionStorage.setItem("items",testArray);
    let storedArray = sessionStorage.getItem("items").split(",");
    let i = 0;
    for (i = 0; i < storedArray.length; i++) {
                 alert(storedArray[i]);
    }
Clone answered 8/10, 2023 at 5:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.