lost9123193 lost9123193 - 3 months ago 25
React JSX Question

Object Property Undefined in Javascript/Redux

I used redux local storage to store the following:

{"id":1,"first_name":"","last_name":"", “hobbies”:{}}


This is how their login info was stored:

localStorage.setItem("token", JSON.stringify(response.data.user));


This is how I'm retreiving the data:

var user_info = localStorage.getItem(("token"));


So user_info is able to show the following:

{"id":1,"first_name":"","last_name”:"", “hobbies”:{}, "created_at":"2016-08-03 18:03:23","updated_at":"2016-08-03 18:03:23"}


NOW I want to access
id
but when I do the following:

var id = JSON.stringify(user_info["id"]);
OR
var id = JSON.stringify(user_info.id);


I keep getting the following error. What is the proper way of accessing a property like "id"?

undefined

Answer

In fact you need to use JSON.parse()instead of JSON.stringify() to parse a JSON object, then after it's parsed you can access its properties.

var json = '{"id":1,"first_name":"","last_name":"", "hobbies":{}, "created_at":"2016-08-03 18:03:23","updated_at":"2016-08-03 18:03:23"}';
var id = JSON.parse(json).id;
document.write(id);