Mansa
Mansa

Reputation: 2325

Getting localstorage object into variables

I ma trying to figure out how to retrieve an object saved into an localStorage. The object is an user from parse.com and are stored like this:

localStorage.setItem("USERDATA", JSON.stringify(data[0]));

When then trying to retrieve it later I am trying to do this:

var user = localStorage.getItem("USERDATA");
user = JSON.stringify(user);
console.log("WHAT: "+user['fname']);

This gives me an log like this:

WHAT: undefined 

When just logging the user variable it looks like this:

WHAT: "{\"sqlID\":48,\"fname\":\"Me\",\"lname\":\"Test\",\"objectId\":\"Iy2JzIi7LH\",\"createdAt\":\"2014-03-01T13:04:28.048Z\",\"updatedAt\":\"2014-03-01T13:04:28.048Z\"}" 

I have been trying this all day but can't find the solution... Please help and thanks in advance :-)

Upvotes: 0

Views: 54

Answers (1)

Johan
Johan

Reputation: 35194

You're doing it the wrong way around. JSON.parse(user)/$.parseJSON(user) to fetch properties

var data = '{\"sqlID\":48,\"fname\":\"Me\",\"lname\":\"Test\",\"objectId\":\"
            Iy2JzIi7LH\",\"createdAt\":\"2014-03-01T13:04:28.048Z\",\"updatedAt\"
            :\"2014-03-01T13:04:28.048Z\"}',
    user = JSON.parse(data);

console.log(user.fname, user['fname']);

http://jsfiddle.net/Bu9vJ/1/

Upvotes: 2

Related Questions