1

I am defining a variable called user. The session storage gets the value of that variable as [object Object], but if I try to get or print different properties I get the following

user.name = I get nothing 
user[0] = I get [

I have tried different ways but I am not able to get the property of that object called name.

Help please!

sessionStorage.user = userSessionStorage;

I get [object Object]

I just need to know how I can get the values of the differents properties

5
  • show your code please Commented May 2, 2017 at 4:37
  • add what you have tried in question Commented May 2, 2017 at 4:38
  • 1
    you may use JSON.stringify(object) to get values. Commented May 2, 2017 at 4:42
  • DId not work. I am still getting [object Object] Commented May 2, 2017 at 4:53
  • @KenethSmith did you checked my answer ? Commented May 3, 2017 at 5:22

3 Answers 3

1

There are a number of different reason why user.name returns undefined. Firstly, name property might not exist in your user object. You can do that by doing this:

Object.keys(user)

and see if the string name is in the output array.

Once you have done that, You can try looping through the properties of user like so:

Object.keys(user).forEach(e => console.log(e + ' = ' + user[e]));
Sign up to request clarification or add additional context in comments.

1 Comment

I got this Error: user.forEach is not a function
0

From the session storage you will get a string, you need to make use of JSON.parse() before getting the value

var usr = JSON.parse(user);
console.log(usr)  // this will log the object from where you can access the properties.

2 Comments

I got JSON.parse: unexpected character at line 1 column 2 of the JSON data
Press CTRL + SHIFT + J to open the Chrome developer tools and then you will be able to see the result you get from your session storage. Can you post that
0

Set the data as a JSON String in session Storage instead of JSON Object.

var userData = JSON.stringify(userSessionStorage);

sessionStorage.setItem("user", userData);

And parse it again to JSON Object from JSON String when you get back from the storage.

var getUser = sessionStorage.getItem("user");

var user = JSON.parse(getUser);

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.