Extracting the Hidden Gems in a Nested Object

My goal is to extract a specific value from a two-level deep object data structure. To begin, I am storing the data in a variable within a function, like so:

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

When I use this line of code:

console.log(userInfo);

The console output looks like this:

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

Specifically, I want to retrieve the "_id" value from this data.

I attempted to access it using:

console.log(userInfo.data._id);

However, my IDE displays an error message:

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

How can I successfully extract the "_id" value in this scenario?

Answer №1

It appears you may be accessing it incorrectly
Please try using userInfo.data._id
In the object's log, you will notice that data is a separate object indicated by curly braces {}, so once you access data, you can then access its properties in the same way as any other object.

I also notice that you are receiving

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

This error suggests that you may have missed parsing the information. To confirm this, execute the following:

Execute->

console.log(userInfo);

Output->

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

Following this:
Execute->

console.log(typeof userInfo);

Output->

"string"

Based on your changes, it seems this is indeed the issue.
Please try:

userInfo = JSON.parse(sessionStorage.getItem('currentUser') );
console.log(userInfo.data._id);

Answer №2

The _id attribute can be found within the data section:

const response = {
    "token":"sometoken.value",
    "data": {
       "_id":"8cd0362c0",
       "phone":"555-4343"
     }
};
console.log(response.data._id)

You could also utilize destructuring for a cleaner look:

const { _id } = response.data;
console.log(_id)

or even simpler:

const { data: { _id }} = response;
console.log(_id);

Answer №3

After some guidance from @jonsharpe, I realized that the solution was to first use JSON.parse on the string. By doing this, I was able to obtain the necessary value for "_id":

retrieveId() {
    if (this.authenticationService.isAuthenticated()) {
        const currentUserInfo = JSON.parse(sessionStorage.getItem('currentUser'));
        console.log(currentUserInfo.data._id);
    }
}

Answer №4

It seems like the string you are dealing with is in JSON format. To work with it, you will need to parse it into an object using JSON.parse() for JavaScript, or $.parseJSON() if you are using jQuery. Your code should now look something like this:

var user ='{"token":"sometoken.value","data":{"_id":"8cd0362c0", "phone":"555-4343"}}';
var k = JSON.parse(user);
alert(k.data._id);

You can find a working example at this Fiddle link. Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a Function Triggered by Clicking Text in Angular 8

Is there a way to create an HTML anchor tag with a click event that triggers a function without causing the page to reload or refresh? <div *ngIf="showOTPResendText"> <p style="text-align: center;">Please wait {{counte ...

Searching and adding new elements to a sorted array of objects using binary insertion algorithm

I'm currently working on implementing a method to insert an object into a sorted array using binary search to determine the correct index for the new object. You can view the code on codesanbox The array I have is sorted using the following comparis ...

What is the best way to ensure that empty strings are not included in the length of my array?

I have encountered an issue with a JSON file that I fetch. The array syllables is capable of holding up to strings max. However, when I exclude 2 words, I end up with 2 words and 2 empty strings. Nevertheless, my front-end still expects 4 "strings". So, it ...

What is the best method for altering a route in React while utilizing Typescript?

I recently started coding along with the ZTM course and am working on a face recognition app. Instead of using JavaScript, I decided to use TypeScript for this project in order to avoid using the any type. However, as a beginner in this language, I'm ...

The output is: [object of type HTMLSpanElement]

<form> <table> <tr> <td>Distance:</td> <td><input type="number" id="distance" onKeyUp="calculate();">m</td> </tr> <tr> <td>Time:</td> ...

Converting a JavaScript List object to a JSON format

I have a pre-existing structure of a class object in my web service that was developed by another team. I am now looking to post JSON data to the CartObject (int CustomerID, List<CartListObject> CartList) class. The elements inside CartListObject ar ...

What is the best way to connect data so that when a user clicks on a specific card, it appears on a popup card

When a user clicks on any card containing data retrieved from a backend API GET method, that data should be displayed in a pop-up card. In my situation, I have two components: DisplayNotes.vue and UpdateNotes.vue. Whenever a user clicks on a displayed card ...

Navigating between interfaces without the need to constantly refresh or reload

Currently, I am in the process of developing a website using ASP.NET MVC that allows users to navigate between pages without refreshing each time. My approach involves treating views as 'areas' or mini master pages, utilizing partial views inste ...

Attempt to retrieve node information using the useStaticQuery method in Gatsby

I am facing an issue where I am trying to retrieve information from GraphQL Gatsby using useStaticQuery, but the data returned is showing as undefined. I am confused as to why this is happening because when I check my http://localhost:8000/___graphql endpo ...

The Discord.js Avatar command does not support mentioning users

Everything seems to be working fine when I check my own avatar, but it doesn't work properly when I mention another user. Here's the code I'm using: client.on('message', message => { if (message.content === `${prefix}ava`) { ...

An error was returned by Ajax when attempting to make the ajax call

I have a custom ajax function that successfully updates my database. After the update, I call the successAlert() function. Now, I want to incorporate an error handling mechanism by calling the error function in case of any errors. However, during testing, ...

Steps for crafting a killer soundtrack with ReactJS using lists

I am currently working on developing a UI feature that allows users to download mp3s from their computer directly to a playlist. So far, I have successfully obtained the name of the song and the correct link pointing to the song. However, I am now faced wi ...

Is there a method to introduce a line break for each piece of data that is shown?

I am currently working with an array and have successfully displayed it on the screen. My inquiry is whether it is feasible to insert a line break for each of the data points it presents. { name: "cartItems", label: "Product Name ...

Customize the label of the model in AngularStrap's typeahead ng-options to display something

Utilizing AngularStrap typeahead for address suggestions, I am facing an issue where I want to set the selected address object as my ng-model, but doing so causes me to lose the ability to display just one property of the object as the label. Here is an e ...

Add values to each entry in a subarray

let b = []; this.state.sidejobs.forEach((user) => { console.log(user); if (!b.hasOwnProperty(user.jobworker)) b[user.jobworker] = 0; b[user.jobworker] += user.duration; }); I have a query regarding splitting and adding durations in entries where ...

24-hour flatpickr timepicker

Can anyone assist me in setting my hour format to 24 hours instead of AM/PM in Angular? I've been struggling with it for the past 2 days. Below are my TypeScript and HTML code snippets: TypeScript: flatpickrOptions: any = { locale: French, enable ...

Tips for converting an asynchronous process to operate as a synchronous process

Hey there! Checkout this piece of code I have function executeBat(){ var process = require('child_process').exec; process('C:\\Temp\\tasks\\acis\\runme.bat', function(error, stdout, std ...

Discovering the data type in Typescript through the use of Generics

In my data structure, I am using generics to build it. However, when I try to populate data, I encounter the need to convert simple formats into the correct types. The issue arises as the class is configured with Generics, making it difficult for me to det ...

Struggling to Keep Track of Namespaces within an Array

Creating a chat application with multiple namespaces allows users to discuss different topics of interest, like 'dogs' or 'cats'. In my initial version, I stored each namespace in a variable and it worked perfectly: Server side: var ...

Guide to uploading a recorded audio file (Blob) to a server using ReactJS

I'm having trouble using the react-media-recorder library to send recorded voice as a file to my backend. The backend only supports mp3 and ogg formats. Can anyone provide guidance on how to accomplish this task? Your help would be greatly appreciated ...