Tips for retrieving information from an object or converting it to a particular data type

I'm struggling to figure out how to convert an undefined object into a defined one in Angular TS. I have a table that allows for content modification using a modal window. The data from the row fills the fields of the modal window, and once changes are made, the returned object is of type Pacient:

constructor(
    public dialogRef: MatDialogRef<pacientModifier>,
    @Inject(MAT_DIALOG_DATA) public data: PacientModif) {
      this.data={...data};        
    }

  onNoClick(): void {     
    this.dialogRef.close({data:this.data});
  }

However, when using dialogRef, the returned result is of an undefined type.

 dialogRef.afterClosed().subscribe(result => {
          this.updateRowData(result);
        });

The returned result is an undefined object with members of the Pacient object.

The Pacient object:

export class Pacient {
id = "";
name = " ";
pacient_Condition =" ";
birth_Date=" ";
}

The object returned after closing the modal window:

data: Object { id: " ", name: " ", pacient_Condition: " ", birth_Date:"" }

I have attempted to cast using result as Pacient or using Object.values(result).

Patient's page template:

<ng-container matColumnDef="actions">
      <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
      <mat-cell *matCellDef="let element">
        <button md-button (click)="openDialog(element)">Edit</button>
      </mat-cell>
    </ng-container>

Open dialog method:

openDialog(row:Pacient): void {
        const dialogRef = this._dialog.open(pacientModifier, {
          width: '250px',
          data: row
        });
        dialogRef.afterClosed().subscribe(result => {
          console.log(result);
          this.updateRowData(result);
        });
      }

Is there a way to access the data member by member (Id, name, etc.) or convert it directly into a Pacient object?

Answer №1

I creatively extracted the values from an array within the result object, utilizing object destructuring and property shorthand for populating the members of a Pacient object.

extractReponse (response : any,pacient : Pacient){
   pacient.id =(({ id}) => ({id }))(Object.values(response)[0] as Pacient)['id'];
   pacient.name=(({ name}) => ({name }))(Object.values(response)[0] as Pacient)['name'];
   pacient.pacient_Condition=(({ pacient_Condition}) => ({pacient_Condition }))(Object.values(response)[0] as Pacient)['pacient_Condition'];
   pacient.birth_Date=(({ birth_Date}) => ({birth_Date }))(Object.values(response)[0] as Pacient)['birth_Date'];
   console.log('in extraction',pacient);
   return pacient;
}

A valuable resource that contributed to my solution: How to get a subset of a javascript object's properties

Answer №2

attempt using

output as unidentified as Individual

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

Encountering an Issue with Vue 3 and Vue Router 4: Uncaught TypeError - Trying to Access Undefined Properties (specifically 'push')

I'm currently working with Vue 3, Vue Router 4, and TypeScript in my project. However, I've encountered an issue while trying to utilize router.push(). Every time I attempt this, I receive a console error stating: Uncaught (in promise) TypeError: ...

Cracked Code at Position 880 (LeetCode)

Given an encoded string S, the decoded string is determined by reading each character and following the steps below: If the character is a letter, it is written directly onto the tape. If the character is a digit (denoted as d), the current tape i ...

Setting up "connect-redis" in a TypeScript environment is a straightforward process

Currently, I am diving into the Fullstack React GraphQL TypeScript Tutorial I encountered an issue while trying to connect Redis with express-session... import connectRedis from "connect-redis"; import session from "express-session"; ...

Exploring the power of TypeScript with React-Router

Struggling to set up react-router with typescript. I've installed @types/react-router, but encountering an error message saying: @types/react-router/index"' has no exported member 'hashHistory' I've experimented with different ro ...

Leverage the power of react-redux useSelector with the precision of TypeScript

When attempting to utilize the new useSelector hook (shown in the example below) from react-redux in TypeScript, an error is encountered indicating that the function does not exist: Module '"../../../node_modules/@types/react-redux"' has no expo ...

update angular component after deleting an item

After deleting a contact in the table, I'm trying to refresh my contact list page but it's not working. Any suggestions? This is the list of contacts in the contact.component.ts file Swal.fire({ title: 'Do you want to delete this contac ...

Utilizing the filter function with serverSide rowModelType in ag-grid

Successfully integrated ag-grid with server side rowModelType implementation. Placed an input textbox above the grid for filtering purposes. When a user types in the search query "abc", it triggers a call to the server with "searchString=abc" included in ...

A specialized React hook designed for fetching data in a continuous loop

Been struggling with this issue for hours :( I have a hook called useCollection which is designed to provide data retrieved from my API and updated in real-time using a websocket. It works perfectly for real-time updates, but I want it to also update the ...

How to handle redirection after login and logout on an Angular Identity Server?

In my Angular project based on .NET Core, I incorporate IdentityServer and customize the Identity Server razor login page. While most of the pages are Angular with lazy-loading features, there are specific scenarios I need to address for post-login and log ...

Mongoose encountered an error when attempting to cast the value "ObjectID" to an ObjectId at the specified path "red.s1"

My Mongoose schema is structured as follows: const gameSchema = new Schema({ matchNumber: { type: Number, required: [true, 'A match must have a number!'], unique: true }, red: { s1: { type: ...

Exploring Angular2 components featuring setInterval or setTimeout functions

I have a basic ng2 component that interacts with a service to retrieve carousel items and automatically cycle through them using setInterval. Everything functions properly, but I encounter the error "Cannot use setInterval from within an async test zone" w ...

Concealing a VueJs component on specific pages

How can I hide certain components (AppBar & NavigationDrawer) on specific routes in my App.vue, such as /login? I tried including the following code in my NavigationDrawer.vue file, but it disables the component on all routes: <v-navigation-drawer ...

Guide on incorporating a custom React element into an Angular 6 project

After creating a React application and defining it as a custom element with customElements.define('react-iis', ReactElement);, I successfully built the application and obtained JavaScript files. Using this element directly within a normal HTML fi ...

What causes the website to malfunction when I refresh the page?

I utilized a Fuse template to construct my angular project. However, upon reloading the page, I encountered broken website elements. The error message displayed is as follows: Server Error 404 - File or directory not found. The resource you are looking fo ...

Transformation of Python code into Blockly blocks

As the founder of edublocks.org, I am interested in adding Python to Blocks functionality on the platform. At the moment, users can only transition from Blocks to Python. Is there anyone who has experience with this and can provide guidance on how to achi ...

How to define a TypeScript recursive object with a defined endpoint?

Welcome to my first question! I am currently facing an issue with defining an object to store strings in multiple languages. I am looking for a flexible solution and have considered using a nested object structure. However, I want the final object to adhe ...

The object literal's property 'children' is assumed to have a type of 'any[]' by default

Is there a way to assign the property myOtherKey with any value? I encountered a Typescript error that says.. A problem occurred while initializing an object. The property 'children' in the object literal implicitly has an array type of 'a ...

Warning: Obsolescence of Typescript Detected

Having an issue with my login code in TypeScript. The 'subscribe' function is deprecated and I'm not sure how to proceed. Can anyone provide some guidance? doLogin() { this.userService.doLogin(this.loginForm.value).subscribe( r ...

Exploring the versatility of Vue.js through props and scoped slots

Coming from a React background, I am used to being able to easily alter children components before they render. However, after spending hours reading the VueJS documentation and searching forums, I have not been able to find a straightforward way to do thi ...

Leveraging the power of literal types to choose a different type of argument

My API is quite generic and I'm looking for a typed TypeScript client solution. Currently, my code looks like this: export type EntityTypes = | 'account' | 'organization' | 'group' export function getListByVa ...