Ademo Ademo - 1 year ago 31
Javascript Question

Pulling Out Value from Within Two-Levels Deep Object

I am trying to retrieve one particular value from within a two-levels deep object data structure. First off, though, I am saving into a variable within the function, like this:

getTargetId() {
if (this.authenticationService.isAuthenticated()) {
const userInfo = sessionStorage.getItem('currentUser');
console.log(userInfo);
}
}


From:

console.log(userInfo);


I get this back in the console:

{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}


What I want to do is specifically pull out the "_id" value here.

I tried:

console.log(userInfo.data._id);

But then my IDE is showing me an error:


'Property '_id' does not exist on type 'string'.


How do I dig out "_id" in this case?

Answer Source

You are accessing it wrong
Try userInfo.data._id
In the log of your object you can see by the {} notation that data is another object, so after accessing data you can access its properties just as you would with any other object.

I also see that you are getting

'Property '_id' does not exist on type 'string'.

This could mean that you never parsed the information. To find out if this is the case this should be right:

Running->

console.log(userInfo);

Returns->

{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"...}

Just after this code:
Running->

console.log(typeof userInfo);

Returns->

"string"

With your edits, I can see that this is the case.
Try:

userInfo = JSON.parse(sessionStorage.getItem('currentUser') );
console.log(userInfo.data._id);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download