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?

1
  • 1
    JSON.parse(sessionStorage.getItem("items"));.. What made you concatenate [ \ ] there.. ? Commented Jun 28, 2016 at 18:04

3 Answers 3

26

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/

Sign up to request clarification or add additional context in comments.

1 Comment

You are amazing! Thank you so much. I had no idea about the JSON.parse function! :D
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.

Comments

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]);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.