Transforming JSON into object instances with Angular

I am facing an issue in my Angular application where I need to convert a JSON object into an array. Although the mapping process is successful, the data within the array does not retain the properties and methods of my original object class. This hinders me from calling any custom functions created within the class.

export class Armor {
name: string;
listOfUpgradeMaterials: Material[];

get externalLink(): string {
    return this.name.replace(" ", "_");
}

Here is how I am performing the conversion:

 // Assuming 'result' is a JSON value with an array of armor objects
 var list = <Armor[]>result;
 console.log(list[0].externalLink); // This does not work as expected
 console.log(list[0].name); // This works fine

I attempted using a custom map function, but it failed to instantiate the 'Material' property of the child objects. Therefore, that approach did not yield the desired outcome either.

this.list = _.map(this.list).map(function (x) {
let armor: Armor = Object.assign(new Armor, x);
return armor;
});

I am seeking advice on a comprehensive solution that can handle such scenarios, even when dealing with multiple levels of nested objects.

Thank you for your assistance.

Answer №1

Creating instances of classes requires the use of the new operator in order to access getters, setters, and methods. One approach is to define fields within the constructor as shown below:

1)

export class Armor {
  constructor(public name: string,
              public listOfUpgradeMaterials: Material[]){}

  get externalLink(): string {
      return this.name.replace(" ", "_");
  }
}

To instantiate, you can utilize the following code snippet:

...
this.list = result.map( item => {
  const { name, listOfUpgradeMaterials } = item;
  const materials = listOfUpgradeMaterials.map(material => new Material(material));

  return new Armor(name, materials);
} )
...

2) Another method involves using Object.assign for both Armor and Material objects:

...
function instantiate(item, clazz){
  return Object.assign(new clazz(), item);
}
...
this.list = result.map( item => {
  item.listOfUpgradeMaterials = item.listOfUpgradeMaterials
    .map(material => instantiate(material, Material));
  return instantiate(item, Armor);
} )
...

3) If you prefer separating all properties like new Armor(name, materials, ...), you can assign fields within the constructor and pass the object as a parameter:

export class Armor {
  public name: string,
  public listOfUpgradeMaterials: Material[]

  constructor(armor: Armor){
    Object.assign(this, armor);
  }

  get externalLink(): string {
      return this.name.replace(" ", "_");
  }
}

Then, you can use new Armor(armorJSON) for instantiation (ensuring that both Material and Armor objects are also instantiated).

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

Employing a section of an intricate map found in the Stores React platform

Take a look at this data stored in Zustand or any other store. productMap: { 'product-id-abc': { info: { name: 'Gmail', url: 'gmail.com', api: 'localhost:8080' }, endpo ...

Having trouble with reloading the FirebaseAuth widget in an Angular 8 single page application?

I recently developed an Angular 8 CLI project that integrates with FirebaseUI Auth for email and password login. However, I am facing an issue where the FirebaseUI Auth widget does not appear after the user logs out. Is this a bug in the system or am I ove ...

Looking to customize the scrollbar style within an Angular Material table?

Is there a standard method for customizing the scrollbar design in an Angular Material table similar to the one displayed below? (I am unable to identify any applicable styling attributes through element inspection.) angular-table-issue ...

Loading an Angular application by sending an HTTP request to populate an array

After developing a simple shopping cart application using Angular 9, I faced an issue where I could only retrieve the product list by triggering a click event. The core functionality of my app involved sending an HTTP request to the server in order to fet ...

Comparing Angular 2's Seed and CLI: A closer look at

Exploring my options for beginning a fresh Angular 2 Project. I stumbled upon angular2-seed and angular-cli as potential tools for kickstarting the project. However, I am deliberating on which one to opt for and curious about their respective advantages a ...

The Angular user interface is failing to update in accordance with the list obtained from the HTTP GET request made to the .Net Core API

Currently, I am working on an application that utilizes Angular for the frontend and .Net Core API 3.0 for the backend. My objective is to display a list of clients using the Angular Material grid. In my OnInit() method, I invoke my getAllClients service t ...

Dealing with router parameters of an indefinite number in Angular 5: A comprehensive guide

Is there a method to efficiently handle an unknown number of router parameters in a recursive manner? For instance: We are dealing with product categories that may have subcategories, which can have their own subcategories and so on. There are a few key ...

typescript's JSON.stringify function includes internal fields but omits public interface values

I'm currently grappling with some confusion surrounding serialization in TypeScript using JSON.stringify and interfaces. My goal is to create an export format for serializing certain objects back to their server-side representation, focusing solely on ...

Excessive loading time for bundle.js production in Angular2

Currently, I'm utilizing angular2 in my project. The following command was used to generate the build. ng build --prod The size of Bundle.js is 1.4MB. In my application, I have integrated angular2-google-maps, bootstrap, and dropzone. Are there an ...

Type of object is unidentified in Vuejs with Typescript error code ts(2571)

Currently, I am facing a challenge with storing JSON data in a variable within my Vue project. Below is the code snippet used to upload and store the file: <input type="file" id="file" ref="fileSelect" class="custom- ...

How to toggle the display of a div by its id using index in Javascript

Currently, I am encountering a problem with toggling the div containers. When I click on the video button, I want the other divs to close if they are already open. However, due to the toggling mechanism, if a div is closed and I click on the corresponding ...

Having trouble retrieving data from Spotify API within Angular application

Upon attempting to retrieve a json response from the Spotify API, I encountered the following error: XMLHttpRequest cannot load https://api.spotify.com/v1/search?query=eminem&offset=0&limit=20&type=artist&market=US. Request header field Ac ...

Strategies for extracting the type argument from a nested property and transforming it into a different value

I’m struggling to find the right way to frame my question, so I’ll provide an example of what I need help with. Let's assume I have the following object: const obj = { one: 'some string', two: new Set<string>(), }; Now, I wan ...

Guide to generating TypeScript output files within a non-hierarchical directory layout

In my project, I have a directory structure with multiple typescript files organized as follows: | src | app-1 | tsconfig.json | app-2 | tsconfig.json | common | standalone | tsconfig.json For each of the ...

Change the ddmmyy date string to dd/mm/yyyy format using TypeScript

When I use the date picker onchange method, the date is passed as a string like ddmmyyyy (20102020) to dd/mm/yyyy. I am unsure of how to convert the date format from ddmmyyyy to dd/mm/yyyy. In the CustomDateParserFormatter, the string needs to be converted ...

Guide to successfully submitting an Angular form that includes a nested component

I have developed a custom dateTime component for my application. I am currently facing an issue where I need to integrate this component within a formGroup in a separate component. Despite several attempts, I am unable to display the data from the child fo ...

Angular: Ensuring Paypal button does not display twice without a hard reload

I have encountered an issue with a PayPal payment button on my page. The button displays fine when I generate it for the first time, but if I try to generate it again for another order, it doesn't show up. I have to hard reload the page to get it to w ...

Angular project models

I'm exploring the Core/Shared/Feature design pattern for building large, scalable applications in Angular, and I find myself unsure about where models fit in. Is there a consensus on which module they belong in? I came across a post suggesting that ...

RxJs Subject: Acquiring the Sender

I have been working with Subjects and there is a .subscribe() in a specific class. Emitting values to this class from different other classes has resulted in the subscribe function being triggered multiple times, yet I am unsure of where these emits are co ...

Discovering the power of Angular 2 with ngrx while putting my Reducer to the

Within my Reducer file: case PumpActionTypes.EnterLocalMode: return commandOne.upsertOne( {id: action.payload.id, changes: { local: false }}, state ); When testing, I aim to verify that the local property is indeed modified to false. My curr ...