Require assistance with transforming a JSON string into an object

I've been struggling with converting the JSON object returned from the service to the Directory class. The issue is that the Directory class has an 'expanded' property which is not present in the JSON object. I've tried various methods over the past few days but haven't had any luck.

Thank you in advance for any help or guidance on this matter.

    export class Directory {
       type: string;
       name: string;
       expanded: false;
       directories: Directory[];
       files: File[];
    }
    export class File {
       type: string;
       name: string;
       fileExtension: string;
       size: string;
       lastModified: string;
       downloadUrl: string;
    }

[
    {
        "type": "directory",
        "name": "DIR A",
        "directories": [],
        "files": [
            {
                "type": "file",
                "name": "FILEN.pdf",
                "fileExtension": ".pdf",
                "size": 1000,
                "lastModified": "2020-06-17",
                "downloadUrl": "http://example.com/filename.pdf"
            },
            {
                "type": "file",
                "name": "FILEN-1.pdf",
                "fileExtension": ".pdf",
                "size": 1000,
                "lastModified": "2020-06-15",
                "downloadUrl": "http://example.com/filename-1.pdf"
            }
        ]
    },
    {
        "type": "directory",
        "name": "DIR B",
        "directories": [],
        "files": [
            {
                "type": "file",
                "name": "FILEN-2.pdf",
                "fileExtension": ".pdf",
                "size": 1000,
                "lastModified": "2020-06-12",
                "downloadUrl": "http://example.com/filename-2.pdf"
            }
        ]
    }   
]

I attempted the following approach:

  this.api.getFileUrl().subscribe((response:any) => {
    let directory: Directory = JSON.parse(JSON.stringify(response));
  });

Upon debugging, I noticed that the 'expanded' property is missing in the directory object. By the way, I am relatively new to Typescript and Angular.

Answer №1

Suppose you possess a JSON object stored in a property called data, simply execute the following:

const parsedData: Omit<Directory, 'expanded'> = JSON.parse(data);

Answer №2

Upon reviewing your proposed solution...

this.api.getFileUrl().subscribe((response:any) => {
    //..
}

For this to be accurate and functional, it is necessary for you to update getFileURL() as follows...

this.api.getFileUrl() = from(fetch('SomeJsonPageOfYours.json')).pipe(
    switchMap(response => response.json())
)

If the data structure does not match your expectations, consider how you are subscribing() to this.api.getFileUrl(). Double-check that you are applying the .json() method correctly on the response object. This area might require further examination (as the corresponding code was not provided).

Answer №3

Construct an interface followed by its implementation:

 export interface IDirectoryStructure {
       category: string;
       name: string;
       subDirectories: Directory[];
       filesList: File[];
    }
     export class Directory implements IDirectoryStructure {
       category: string;
       name: string;
       open: false;
       subDirectories: Directory[];
       filesList: File[];
    }

Next, utilize the defined interface:

this.api.getFileUrl().subscribe((res:any) => {
    let folder: IDirectoryStructure = res;
  });

Answer №4

It's important to note that the type defined in TypeScript does not have any effect during runtime.

In this scenario, the Directory class seems to only have the value of expanded as false, which we can then assign to the response object.

To achieve this, you can follow these steps:

// excluding the expanded property from the Directory type
type IGetFileUrlResponse = Omit<Directory, 'expanded'>; 

this.api.getFileUrl().subscribe((response: IGetFileUrlResponse) => {
    // creating a valid Directory type by adding the expanded property
    let directory: Directory = {
       ...response,
       expanded: false,
    };
 });

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

Typeorm issue: Foreign key insertion not functioning correctly with cascade enabled

I currently have a situation where I am dealing with 2 entities that have a ManyToOne/OneToMany Relation with cascade enabled. < One: Sender ---- Many: Transfer (cascade insert) > My goal is to add 2 new Transfer instances with the same sender. How ...

"Update your Chart.js to version 3.7.1 to eliminate the vertical scale displaying values on the left

https://i.sstatic.net/7CzRg.png Is there a way to disable the scale with additional marks from 0 to 45000 as shown in the screenshot? I've attempted various solutions, including updating chartjs to the latest version, but I'm specifically intere ...

Demonstrate HTML and CSS integration through the use of the http.get method

In an attempt to create an iframe-like solution, I am using an http.get call to retrieve a site as an object containing HTML and CSS. The issue arises when using <link> tags because the CSS path is obtained from an external source, causing the HTML t ...

The Angular Syncfusion schedule is unable to call upon an object that may potentially be 'undefined'

Currently, I am developing an application using Angular Syncfusion to allow users to view and book appointments. I found a helpful resource at the following link: Below you can find the code snippet I have been working on: <ejs-schedule #scheduleObj ...

To access the value of a DOM input in an Angular component, utilize the "renderer/renderer2" method

Recently, I embarked on my journey to learn Angular. One of my goals is to retrieve data from a form and store it in a database (Firebase) using angularfire2. While going through the documentation, I noticed that there is a "setValue()" method available b ...

Tips for utilizing the "this" keyword in TypeScript

As a newcomer to TypeScript, I am seeking assistance on how to access the login service within the authenticate function. Despite using the 'this' keyword to retrieve the login service, it seems ineffective. Additionally, I find myself puzzled by ...

Running multiple Angular projects on IIS 10

Currently, I am faced with the task of deploying three Angular applications on IIS 10. It is essential that routing functions correctly for all scenarios across all applications. Each application is stored in its own folder, such as 'first-app', ...

Tips for handling numerous requests using Express.JS

I am currently working on an Angular 6 + Express.JS application and have encountered a problem. When multiple requests are made simultaneously, especially when there are more than 4 requests, all of them sometimes respond with a 404 error or get cancelled. ...

Mapping type keys to camelCase in Typescript: a guide

As someone who is relatively new to typescript, I am eager to learn how to create a mapped type that converts keys from one type to another. Specifically, if I have a type where all the keys are written in snake case, how can I create a new type with camel ...

Issues with Typegoose and Mongoose Enums when utilizing an array of strings

One of my enums is defined as follows: export enum Careers { WEB_DEVELOPMENT = 'Web Development', MOBILE_DEVELOPMENT = 'Mobile Development', UI_UX = 'UI/UX' } This particular enum is used as a mongoose property like so: ...

Struggling with the functionality of Angular Material Layout Directives

Looking to implement the Child-Alignment feature in Angular Material but running into some issues. Details available here: https://material.angularjs.org/latest/layout/alignment Despite trying to import import { LayoutModule } from '@angular/cdk/l ...

What is the process for establishing a universal timeout for GET requests in angular2?

I'm in the process of implementing a timeout for all requests in my Angular2 app that uses http. Currently, I have successfully added a timeout for a single request like this: this.http.get(this.endPoint) .timeout(10000, new Error('timeout&apo ...

How can I retrieve all the recipes associated with a specific user (id) using ASP.NET Core 3.1.1 MVC and Angular?

Currently delving into ASP.NET MVC, I am immersed in building a single-page application using ASP.NET Core 3.1.1 with APIs. Within my User.cs file, there exists a collection of the user's Recipes. Specifically, within my User class, there is a prope ...

Building an Angular docker file is quite time-consuming

I am currently using a Dockerfile to build and run my project. The process of building the Docker image takes around 10-15 minutes, which seems quite long compared to the npm run build command that only takes 2-3 minutes. Do you have any suggestions on h ...

Error: The 'address' property cannot be found in the specified 'string' type

Hey there! I'm currently facing an issue while trying to pass an object from one page to another and store it in the object on the second page. I'm encountering an error with EsLint. let accountDetails:any={ name:this.userAccount.name, p ...

Display spinner exclusively for prolonged requests using Angular's HttpInterceptor

I developed a custom interceptor that displays a spinner whenever an HTTP request is initiated: import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Injectable } from '@angular/core'; im ...

Upgrade of Angular 2 to rc 5 presents with unresolved peer dependencies

I am looking to update my angular version to rc5 in order to utilize NgModule. Following the directions provided by Angular 2. I have made changes to my package.json dependencies and then executed npm stall in the terminal: ... The results from the ter ...

Variations in key options based on specific situations

Is it possible to make certain keys required in Typescript depending on the circumstances? For instance interface IDog { name: string; weight: number; } class Retriever implements IDog { name = "Dug"; weight = 70; public updateAttribute(props ...

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

Model driven forms in Angular 4 do not display validation errors as expected

I'm having trouble getting validation errors to display with the code below. Can anyone provide some assistance? I've set the validators in my component using Form builder. The validation works when I use a single form-group, but it's not w ...