Converting JSON to TypeScript with Angular Casting

I'm facing an issue detailed below.

API:

 "Data": [
  {
    "Id": 90110,        
    "Name": "John",
    "Surname": "Doe",       
    "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472d282f2923282207202a262e2b6924282a">[email protected]</a>",    
    "Status": "Active"
  },
  {
    "Id": 90109,
    "Name": "Sally",
    "Surname": "Doe",        
    "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f281939e9e8b969d97b2959f939b9edc919d9f">[email protected]</a>",  
    "MiddleName":"II",           
    "Status": "Active"
  }]

Upon parsing the JSON to my typescript class, I noticed that the MiddleName property remains undefined. This is causing issues when exporting to Excel using the 'xlsx' library as shown in the image below. How can I address this problem and set a default value for null or undefined properties?

User Export P.S : I am using 'xlsx' library for excel export.

Answer №1

In order to assist you with debugging, it would be helpful if you shared the code for your TypeScript class where you parsed the JSON data. Without that information, we are unable to provide specific assistance.

However, if you have created a class that mirrors the structure of the JSON data and want to handle missing properties by assigning them empty strings, you could use the following approach after receiving the API response:

const data = apiJson.map( (person) => {
    Object.assign(
       new Person(), 
       {
         Id: person.Id,
         Name: person.Name || '',
         Surname: person.Surname || '' ,        
         Email: person.Email || '',  
         MiddleName: person.MiddleName || '',           
         Status: person.Status || ''
       }
    )
});

If your class only contains property definitions without any methods, you might consider defining it as an interface instead. In this case, you can simplify the mapping process like so:

const data = apiJson.map( (person) => {
       return {
         Id: person.Id,
         Name: person.Name || '',
         Surname: person.Surname || '' ,        
         Email: person.Email || '',  
         MiddleName: person.MiddleName || '',           
         Status: person.Status || ''
       }
 });

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

Adjust dropdown options based on cursor placement within textarea

I have a textarea and a dropdown. Whenever a user selects an option from the dropdown menu, it should be inserted into the text area. However, I am facing a bug where the selected value is being inserted at the end of the text instead of at the current cur ...

Encountering an unexplained JSON error while working with JavaScript

I'm trying to retrieve data from a JSON API server using JavaScript AJAX and display it in an HTML table. However, I keep encountering an undefined error with the data displaying like this: Name id undefined undefined This is my code snippe ...

Validation parameters provided during the Palantir workshop

At our Palantir workshop, we utilize a form to input values that are then added to an Ontology object. Recently, I've been tasked with validating the combination of userId, startdate, and states from the form inputs to check if they already exist or n ...

Angular/Typescript: develop a factory function that creates objects based on the parent class's properties

I'm currently working on implementing a factory method that can return classes dynamically, and here's my code snippet: getWidget<T extends WidgetBase>(componentName: string): Type<T> { switch (componentName) { default: ...

Modify the ngb-timepicker formatting to output a string instead of an object

I am currently working on modifying ngb-timepicker so that it returns a string instead of an object. Right now, it is returning the following format: { "hour": 13, "minute": 30 } However, I want it to return in this format: "13:30" This is the HTM ...

Receiving identical data in various smart components

Seeking recommendations on simplifying code that requires subscribing to the same data in multiple Angular smart components. For instance, consider this repetitive code: public item: Item | undefined; public ngOnInit(): void { this.items$.subscribe(a ...

Checking for unnecessary properties in Typescript with vue-i18n

Let's consider two different languages represented in JSON format: jp.json { "hello": "こんにちは" } ge.json { "hello": "hallo", "world": "welt" } Now, we are going to com ...

Routing in Angular 2 with .NET Core

I am experiencing an issue with my ASP.NET CORE app that utilizes angular2 routing. When I run the app locally, the routes work as expected. However, once I publish it to the server (running IIS 7), the routes seem to resolve to the server root instead of ...

Prevent tooltip text from appearing when a button is disabled in an angular application

As a beginner in UI development, I have a requirement for my Angular application. I need to enable and disable a button based on certain conditions. The tricky part is that I want to display a tooltip only when the button is enabled. I have managed to chan ...

Implementation of a recursive stream in fp-ts for paginated API with lazy evaluation

My objective involves making requests to an API for transactions and saving them to a database. The API response is paginated, so I need to read each page and save the transactions in batches. After one request/response cycle, I aim to process the data an ...

Implementing CORS headers in both Angular 9 frontend and Django 3 backend for seamless communication

Struggling to properly configure a front-end app in Angular 9 that consumes a RESTful backend web service. I have my Angular development server running on a remote server with a static IP using ng serve --host 0.0.0.0 --port 80 so it can be accessed extern ...

Error while conducting unit testing: Element 'X' is unrecognized

While running the command npm run test, I encountered a specific error in my terminal: 1. If 'app-general-screen' is an Angular component, then verify that it is a part of an @NgModule where this component is declared. 2. If 'app-general-sc ...

The function cb() was never invoked, resulting in an error during the npm install process

I'm having trouble installing node modules in my angular project. Running npm install gives me this error: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <https://npm.community> ...

Saving json data into an SQLite database with the help of nodeJS

I'm completely new to Javascript and I'm attempting to save a json file into the database. However, I've encountered an error that is causing some issues: $ node db.js module.js:339 throw err; ^ Error: Cannot find module './comm ...

Issues arise when HTML components are not functioning correctly upon calling JSON

I'm encountering a challenging issue that's difficult to articulate. Here is a link to a JSFiddle that demonstrates the problem: https://jsfiddle.net/z8L392ug/ enter code here The problem stems from my utilization of a news API for F1 stories. W ...

Displaying a component upon clicking a button in Angular 9

Within the navbar, there is a "+" button that triggers the display of the component. <app-navbar></app-navbar> Upon clicking the button, the <app-stepper></app-stepper> component should be shown. <app-navbar></app-navba ...

Tips for reverting from Angular 7 to Angular 6

I attempted to switch from angular 7 back to angular 6 by executing the following npm commands: npm uninstall -g angular-cli npm cache clean npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32535c55475e53401f515e5 ...

`Only encountering CORS access-control-allow-origin issue when using Safari browser`

We have an Angular application that communicates with a .NET Core RESTful API project. In addition, we have a separate authentication application (Identity Server4) responsible for managing logins. This issue is specific to Safari; all other browsers are ...

Compiling TypeScript to JavaScript with Deno

Currently experimenting with Deno projects and looking for a way to transpile TypeScript into JavaScript to execute in the browser (given that TS is not supported directly). In my previous experience with NodeJS, I relied on installing the tsc compiler via ...

Obtain redirected JSON data locally using Angular 5

Currently, I am working on retrieving JSON data which will be sent to my localhost through a POST method. The SpringBoot API controller will validate the JSON content before forwarding it to my localhost. My task is to intercept this JSON data when it is t ...