Discovering a Specific Value in a JsonObject

I have encountered an issue with retrieving data from my Json Object as I keep getting undefined values,

{
    "status": 200,
    "message": "Task has been Retrieved",
    "employeepanel": {
        "taskno": 7,
        "taskdate": "2001-06-21",
        "createdby": "admin",
        "taskdescription": "create the product and deliever it by monday  ",
        "status": "assigned",
        "date": "2001-06-21",
        "tenure": 1,
        "employee": {
            "userId": 30,
            "userName": "xyz",
          
        }
    }
}

The objective was to find the task by id, with the API responding in this specific format. Now, I am trying to extract the userName from the response.

findbyId(event) {
    var selected_id = event.currentTarget.id
    const base_URL = 'http://localhost:8091/getbyTaskno/'+selected_id 
    this.http.get(base_URL, {
    }).subscribe(data => {
      if (data['status'] == '200' && data['message'] == 'Task has been Retrieved') {
      this.userIds=data['employeepanel.employee.userName']
     }else{
       alert("No task is present for the particular Employee")
     } })
  }

Answer №1

Consider utilizing dot notation to access your properties and sub properties:

By using dot notation, you can access this.userIds=data.employeepanel.employee.userName;

Answer №2

data['employeepanel.employee.userName']
is not the correct notation to access the username of an employee.

Here is a sample code snippet that demonstrates how to access the user name from a JSON object:

findbyId(event) {
    var selected_id = event.currentTarget.id;
    const base_URL = 'http://localhost:8091/getbyTaskno/'+selected_id;
    this.http.get(base_URL, {
    }).subscribe(data => {
        if (data.status === '200' && data.message === 'Task has been Retrieved') {
            this.userIds=data.employeepanel.employee.userName;
        } else {
            alert("No task is present for the particular Employee")
        }
    });
}

For a comprehensive guide on JSON syntax, you can refer to this resource.

let data = {
    "status": 200,
    "message": "Task has been Retrieved",
    "employeepanel": {
        "taskno": 7,
        "taskdate": "2001-06-21",
        "createdby": "admin",
        "taskdescription": "create the product and deliever it by monday  ",
        "status": "assigned",
        "date": "2001-06-21",
        "tenure": 1,
        "employee": {
            "userId": 30,
            "userName": "xyz",
        }
    }
};

function getEmployeeUserName() {
  console.log("data.employeepanel.employee.userName is: ", data.employeepanel.employee.userName);
}
.main {
  font-size: 20px;
}
<p class="main">Click the button to log the <code>.employeepanel.employee.userName;</code></p>
<button onclick="getEmployeeUserName()">Get Employee userName</button>

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

issue with Angular: Unable to set both minimum and maximum values in the same input field for date type

I have been attempting to apply minimum and maximum values to an Angular code snippet, here is what I have: <input type="date" class="form-control" style="width: 30%" [disabled]="!dateSent" min="{{dateSent|date:&apo ...

Can you please explain the distinction between the .ts and .tsx file extensions? They are both commonly used for TypeScript files in a React environment, but what is the specific use case for each

Hello, I'm in the process of learning React and as I work on my project, I've noticed files with both the .ts and .tsx extensions. I'm a bit confused about when to use .ts versus .tsx. Any guidance on this topic would be greatly appreciated. ...

Is it advisable to switch all properties to Angular Signals?

Recently, I've been utilizing signals to replace certain properties in my components that would typically require computed logic or be reactive to the effect hook. It got me thinking - should I be replacing all of my properties with signals, even if t ...

Obtaining the dimensions of an Angular component: Height and Width

I'm dealing with a component that is manually resized, so I've set up a listener: @HostListener('window:resize') public detectResize(): void { // extract the height and width of the component this.theHeight = // the height of ...

Angular type error: Attempting to assign a value of type 'string' to a variable declared as type 'string[]' is not allowed

As a newcomer to Angular, I am currently working on building an electron app with Angular 6. My objective is: 1. Implementing SupportInformationClass with specific definitions 2. Initializing the component to populate the definitions from electron-settin ...

Issue obtaining information from Firestore and presenting it visually on the screen

I have been working on developing a website using Angular and Firebase. The site allows different users to create accounts, and registered users can add contacts to the Firestore database. However, I have encountered a problem where the added contact info ...

Struggling with the error message "Type 'ChangeEvent<unknown>' is not assignable to type 'ChangeEvent<MouseEvent>'" while working with React and TypeScript? Here's how you can tackle this issue

Within the App.tsx file, I encountered an issue with the Material UI Pagination component where it was throwing an error related to type mismatch. The error message stated: Argument of type 'ChangeEvent' is not assignable to parameter of type &ap ...

Error Encountered | Invalid Operation: Unable to access attributes of undefined (referencing 'CodeMirror')

Error image on chrome Using Next.js 13 Encountering an error on Google Chrome, seeking a solution to fix it or possibly just ignore it. Not utilizing Codemirror and prefer not to use it either. Tried troubleshooting methods: Deleting ".next","node_ ...

When I attempt to run 'ionic cordova build android --prod', I am receiving the following warnings

''' Configure project :app WARNING: The onesignal-gradle-plugin MUST be before com.android.application! Please put onesignal-gradle-plugin first OR update to com.android.tools.build:gradle:3.0.0 or newer! WARNING: Configuration 'compile ...

Displaying text on a ribbon in Excel using Office JavaScript

Currently, I am working on an excel-addin project utilizing Angular and the Office JS API. My goal is to showcase a text message in an angular toast, while also displaying regular text on the right side of the ribbon/menu bar in Excel. My desired function ...

What is the best way to arrange items by utilizing the Array index in JavaScript?

Currently, I am attempting to make the elements within this angular component cascade upon loading. The goal is to have them appear in a specific layout as shown in the accompanying image. I'm seeking guidance on how to write a function in the TypeSc ...

In order to use the serve command, it is necessary to run it within an Angular project. However, if a project definition cannot be located

An error occurred while running the ng serve command: C:\Mysystem\Programs\myfwms>ng serve The serve command needs to be executed within an Angular project, but a project definition could not be found. I encounter this error when ...

Add a css class to a <div> that is created by an <ng-template> inside the <ngx-datatable-column> element

I am struggling to implement the display: flex style on the parent <div> containing my <span> However, since the <span> is dynamically generated by the ng-template of the ngx-datatable-column, I'm finding it challenging to apply thi ...

The HTTP request is failing to transmit cookies

Running an angular application on port 4200 and a flask python backend on port 8080 locally presented some challenges with setting cookies. To resolve this issue, I modified the /etc/hosts file to include the domain for both applications: 127.0.0.1 ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

Auth.logout() callback in AngularFire 2

As I attempt to log out and then navigate to a login URL, I encounter an issue with the authguard preventing logged-in users from accessing it. Due to the asynchronous nature of the operation, clicking the method event twice seems to be necessary for it to ...

Sources of the TypeScript library in WebStorm

I'm brand new to TypeScript. I decided to use WebStorm because I'm familiar with JetBrains tools. In other programming languages, I'm used to having a workflow that includes some kind of dependency management system like Maven, which allows ...

When working with Laravel and submitting a form using the `multipart/form-data` encoding type, you may encounter the

When sending a request that includes form data object with some data from angular 4 to laravel api, sometimes the request data is received correctly and other times it is null, referred to as 'empty request.' Below are the details of my request: ...

Parent variable in Angular Type Script causing undefined error

Can anyone explain why I keep receiving an undefined error? export abstract class BaseEditorComponent implements IPropertyEditor, OnDestroy { @Input() public element: BpmnJS.IRegistryElement; --more code here export class CommonPropertiesEditorCo ...

A comprehensive guide on constructing a literal object in Typescript by combining an array with an object

Recently, I came across this Typescript code snippet: type SortedList = T[] & {_brand: "sorted" }; function binarySearch<T>(xs: SortedList<T>, x: T): boolean let low = 0; let high = xs.length - 1; while (high ...