1

I want to loop through each array of my saved localstorage, but with this code

localStorage.setItem("fav", JSON.stringify(merchant));

                var savedMerchant = JSON.parse(localStorage.getItem("fav"));

                $.each(savedMerchant,function(){
                    console.log(this);

                });

why got this??

String {0: "L", length: 1, [[PrimitiveValue]]: "L"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
VM420:210 String {0: "z", length: 1, [[PrimitiveValue]]: "z"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
VM420:210 String {0: "d", length: 1, [[PrimitiveValue]]: "d"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
VM420:210 String {0: "Z", length: 1, [[PrimitiveValue]]: "Z"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
VM420:210 String {0: "l", length: 1, [[PrimitiveValue]]: "l"}
VM420:210 String {0: "o", length: 1, [[PrimitiveValue]]: "o"}
VM420:210 String {0: "r", length: 1, [[PrimitiveValue]]: "r"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
4
  • 1
    Can you post what did you save to the localStorage and how? It looks like a human readable representation of a JSON object. Commented May 30, 2015 at 3:21
  • Unless you stored a string representation of JSON object in localStorage, there's no need to JSON.parse it. As Eric, said, please edit your question with the code and data that sets the localStorage so that we can see what's going on. Commented May 30, 2015 at 3:26
  • 1
    You're doing your console.log different than your JSON.parse... If your console.log works, seems like you should be doing JSON.parse(localStorage.getItem("fav")) Commented May 30, 2015 at 3:27
  • @SethMcClaine I did.. but what's wrong now? Commented May 30, 2015 at 3:36

1 Answer 1

1

TL;DR

  1. ensure serialization/deserialization using JSON.stringify and JSON.parse()
  2. ensure type is array and encoded before writing to localStorage

The following statement with JSON.parse() implies that localStorage["fav"] is encoded as JSON using JSON.stringify():

var savedMerchant = JSON.parse(localStorage.getItem("fav")); 
// access to localStorage using getItem() corrected from 
// @Seth McClaine in comments to question. Good spot!

So ensure that type you are encoding is also an object using typeof(x) === 'object' with x.isArray() to validate or debug before writing to localStorage.

Hope this helps.

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

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.