Customizing key values within nested objects in Angular2: A comprehensive guide

I need assistance with setting up a JSON object for a post in Angular2/Typescript. I am trying to dynamically set the nested object values for a key. Is it possible to achieve this using Angular2/Typescript?

I have attempted to retrieve the values from JSON and dynamically set them using a repetitive function call. I believe recursion may be the solution. Can someone guide me on how to implement recursion for this function?

let encounterPayLoad = {  
      patient:this.orderEncounter.patient.uuid,
      visit:this.orderEncounter.visit.uuid,
      encounterType:this.orderEncounter.encounterType.uuid,
      obs:[  
         {  
            groupMembers:[  
               {  
                  concept:val,//setting concept values as dynamically
                  value:"1000"
               },
         }
      ],
      orders:[  
      ],
      encounterProviders:[  
         {  
          provider: this.appConstants.defaultProviderUUID,
          encounterRole: this.appConstants.defaultEncounterRoleUUID
         }
      ]
   }
   this.groupMember.push(encounterPayLoad);
   console.log("@payLoad",this.groupMember);
  }

I am aiming for the final object structure as shown below. Currently, it only works at one level inside groupMembers.

{  
   "patient":"e56faafe-70e2-422d-a260-a1c69e72a54c",
   "visit":"7848a99a-323b-4873-9711-2b5f27be86f9",
   "encounterType":"7c179057-ae3d-44d8-b9e7-f5e514992f41",
   "obs":[  
      {  
         "groupMembers":[  
            {  
               "concept":"4876e25c-f580-4a84-9357-a283de220b44",
               "value":"1000"
            },
            {  
               "concept":"964f1f1e-7c26-4e59-bb23-692a4ae02c6f",
               "value":"2000"
            },
            {  
               "concept":"02f962f7-c864-474e-a63a-56feed2ad2dc",
               "value":"3000"
            }
         ],
         "concept":"745449b2-c0e6-4f23-8428-942499142533",
         "order":"0472a6fe-63c5-40f9-b761-dbfa6f91e117"
      }
   ],
   "orders":[  

   ],
   "encounterProviders":[  
      {  
         "provider":"f9badd80-ab76-11e2-9e96-0800200c9a66",
         "encounterRole":"240b26f9-dd88-4172-823d-4a8bfeb7841f"
      }
   ]
}

Answer №1

If you're looking to create a unique string, you may want to consider using a UUID (Universally Unique Identifier). There are various functions available online that can help you generate UUIDs using JavaScript.

For example, here's a function you can use to create a UUID courtesy of JavaScript: Function to create a UUID identifier:

function create_UUID() {
  var dt = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (dt + Math.random() * 16) % 16 | 0;
    dt = Math.floor(dt / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}

You can incorporate this function into your code by calling it as follows:

let encounterPayload = {
  patient: this.orderEncounter.patient.uuid,
  visit: this.orderEncounter.visit.uuid,
  encounterType: this.orderEncounter.encounterType.uuid,
  obs: [{
      groupMembers: [{
          concept: create_UUID(),
          value: "1000"
        },
      }
    ],
    orders: [],
    encounterProviders: [{
      provider: this.appConstants.defaultProviderUUID,
      encounterRole: this.appConstants.defaultEncounterRoleUUID
    }]
  }
  this.groupMember.push(encounterPayload);
  console.log("@payLoad", this.groupMember);
}

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

What is the best way to employ the pick function with optional types within nested TypeScript structures?

I am interested in learning TypeScript. dynamicContent?: { data?: { attributes?: { baccarat?: { title?: string | null; content?: string | null } | null; baccaratOnline?: { title?: string | null; content?: string | null } | null; ...

Stopping the subscription to an observable within the component while adjusting parameters dynamically

FILTER SERVICE - implementation for basic data filtering using observables import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { Filter } from '../../models/filter.model'; imp ...

What is the best way to shift focus to the next input field once the character limit has been reached, especially when the input is contained

My challenge lies in having six input fields arranged side by side in a single row: In my component.html file: onDigitInput(event: any) { let element; if (event.code !== 'Backspace') element = event.srcElement.nextElementSibling; consol ...

Warning: Potential spacing issues when dynamically adjusting Material UI Grid using Typescript

When working with Typescript, I encountered an error related to spacing values: TS2322: Type 'number' is not assignable to type 'boolean | 7 | 2 | 10 | 1 | 3 | 4 | 5 | 6 | 8 | "auto" | 9 | 11 | 12'. No lint errors found Version: typesc ...

My React hooks are failing to properly update the state using useState

I have been encountering an issue with the code in my component where the state is not updating as expected. When I invoke the createUserList function, I can view the users in the UserList component. However, when I attempt to log the users in the UserCom ...

Guide on transforming a tuple of random types into a nested type structure with the help of recursive conditional types

When I responded to the query on whether Typescript Interfaces can express co-occurrence constraints for properties, I shared the following code snippet: type None<T> = {[K in keyof T]?: never} type EitherOrBoth<T1, T2> = T1 & None<T2&g ...

mongoose memory leak attributed to jest

UPDATED 2020-09-14 I've encountered an issue with a test case I wrote. While the testcase passes, it raises a complaint about improper teardown and an open connection. Can anyone help identify the problem: Approach to Solving the Issue - Memory Leak ...

Load page with sorted column in PrimeNg's <ptable> element

Utilizing primeNg's <p-table> component to showcase data in the following structure: HTML <p-table [value]="documents"> <ng-template pTemplate="header"> <tr> <th [pSortableColumn]="&apos ...

What is the proper way to add additional properties to an array object when initializing it in TypeScript?

Is there a more elegant solution for creating an object of type: type ArrayWithA = [number, number, number] & { a: string }; I accomplished this by: const obj : any = [1, 2, 3]; obj.a = "foo"; const arrayWithA : ArrayWithA = obj as ArrayWith ...

Tips for applying unique scss classes to a div based on a specific condition

Currently, I am developing a chat application where I want to showcase messages from one specific user on the right side of the screen while displaying messages from other users on the left side. <ion-item *ngFor="let message of messages | slice:0: ...

I'm baffled as to why TypeScript isn't throwing an error in this situation

I anticipated an error to occur in this code snippet, indicating that b.resDetails is possibly undefined, however, no such error occurred. Can someone please provide an explanation for this unexpected behavior? I'm quite perplexed. type BasicD ...

Combining type inference validation and authentication middleware in Express routes can be a powerful way to enhance security and ensure

I am struggling to grasp how types are automatically determined in Express routes when utilizing multiple middlewares. To conduct validation using zod, I have employed the middleware package express-zod-safe, although a similar issue arose with alternativ ...

Understanding File Reading in Angular/Typescript

I'm currently developing an app similar to Wordle and I'm facing an issue with reading words from a file. Here's what I tried: import * as fs from 'fs'; const words = fs.readFileSync('./words.txt', 'utf-8'); con ...

Adding a dynamic index from ngFor to an HTML attribute value can be accomplished by incorporating the current

I am using ngFor and I am trying to make an attribute inside the loop change its value by adding the ngFor index. This means that each div created within ngFor will have a unique attribute value. Source: <div class="class1" *ngFor="let item of items; l ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

Tips for getting Angular Ivy and Angular Universal up and running together

I'm encountering a problem while attempting to incorporate Ivy + Angular Universal into my project. This issue only arises when I enable Ivy mode in Angular (disabling it allows me to successfully build my application). Below are the steps to replic ...

Encountered a problem with AngularUniversal prerendering: UnhandledPromiseRejectionWarning: Unable to locate NgModule metadata for 'class{}'

Objective The task may seem lengthy, but it's straightforward! Currently, I am utilizing Angular Universal for Server-Side Rendering (SSR) by following a tutorial. The Universal/express-engine has been installed, main.js is generated in the dist/pro ...

ng2-toastr in conjunction with akveo/ng2-admin - Styles not being applied

I recently integrated ng2-toastr into my akveo/ng2-admin dashboard, utilizing the latest version with Angular 4. Following the provided installation documentation, I imported the necessary CSS in the index.html file and declared ToastModule in the app.modu ...

Exploring Angular 2, JavaScript, Efficiency in Memory Consumption, and the Importance of Garbage

I am feeling completely lost and on the verge of giving up on implementing Angular 2 for building a real-world application due to memory usage issues. Despite following all the best coding practices such as nulling properties when no longer needed, removi ...

Getting access to a child component function within the UI-VIEW in Angular 2

I am working on a project that involves both angular 1.5 and angular 2. In my project, I have two sibling components: First-component and Second-component. The First-component contains a Toggle button, while the Second-component has a UI-View of angular 1. ...