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

Unraveling a Java String with HTML elements into a JsonObject: Step-by-step Guide

Hey there, I have a Java String that was received from an HTTP request and it looks like this: {SubRefNumber:"3243 ",QBType:"-----",Question:"<p><img title="format.jpg" src="data:image/jpeg;base64,/9j/4AAQSkZJRgAB..."></img></p>"} ...

Retrieve a specific nested key using its name

I am working with the following structure: const config = { modules: [ { debug: true }, { test: false } ] } My goal is to create a function that can provide the status of a specific module. For example: getStatus("debug") While I can access the array ...

Even with manual installation, the npm package still encounters dependency errors

Having trouble implementing the Imgur package from NPM into my Angular web app. The installation and import seemed to go smoothly, but when initializing a variable with the package, I encounter compile errors pointing to missing dependencies like 'cry ...

Is it better to DeepCopy the List<T> instead of instantiating new instances from JSON?

Having a List of objects such as List<Employee>, each employee in the list is loaded from a .JSON file. I also need to generate new instances based on List<Employee> and only modify the properties of the new instance for the new employee creati ...

Having trouble uploading a JSON array file to your Elasticsearch index?

I've been attempting to upload a json array file into elasticsearch using the commands below: curl -XPOST 'http://localhost:9200/unified/post/1' -d @unified.json as well as curl -XPOST 'http://localhost:9200/unified/post/_bulk' ...

Resolve the Typescript issue that occurs while modifying MuiDataGrid within createTheme

I am trying to customize my DataGridPro table, which is a MUI component, within the theme. However, when I add MuiDataGrid to the components object, I encounter a TypeScript error: Object literal may only specify known properties, and 'MuiDataGrid&apo ...

How to pass a null parameter with jquery's .ajax method

I am facing the following scenario function AddData(title, id) { $.ajax({ type: "POST", url: "topic.aspx/Add", data: JSON.stringify({ "title": title, "id" ...

What is the most effective method for comparing and updating objects within arrays or lists in frontend Angular applications using TypeScript?

While I acknowledge that this approach may be effective, I am of the opinion that there exists a superior method to accomplish the same goal I have two separate lists/arrays containing distinct objects, each with a common attribute. My objective is to ite ...

Angular is having trouble with the toggle menu button in the Bootstrap template

I recently integrated this template into my Angular project, which you can view at [. I copied the entire template code into my home.component.html file; everything seems to be working fine as the CSS is loading correctly and the layout matches the origina ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...

How do I retrieve a specific value from the JSON response using JSONObject?

I have a response with important values that I need to extract. private void getDataFromDistanceMatrixToSaveAndAddToList( GRATestDataImport place, String response) { JSONObject responseAsJson = new JSONObject(response).getJSONArray("rows&q ...

Can you provide guidance on how to access my account using the code that I have?

I'm having trouble getting the login functionality to work properly with this code. When I click the login button, nothing happens - no errors are displayed either. Can you help me identify what might be causing this issue? login() { var url = &ap ...

Is there an issue with TypeScript and MUI 5 sx compatibility?

Here's a question for you: Why does this code snippet work? const heroText = { height: 400, display: "flex", justifyContent: "center", } <Grid item sx={heroText}>Some text</Grid> On the other hand, why does adding flexDirection: "c ...

Having trouble adding items to ListView from ArrayList

CategorySelectionActivity.java public class CategorySelectionActivity extends ListActivity { private ListView listView; //ArrayAdapter<FoodStores> arrayAdapter; private ArrayList<FoodStores> foodStor ...

Utilizing Array Notation in Typescript to Retrieve Elements from Class

In my programming project, I am working with two classes: Candles and Candle. The Candles class includes a property called list, which is an array containing instances of the Candle class. class Candles { public list: Array<Candle>; } class Candl ...

The data from the Ajax request failed to display in the table

JavaScript Code

$(function (){ $.ajax({ type : 'GET', url : 'order/orders.json', dataType : 'JSON', success: function(data) { /*var trHTML = ''; $.each(orders, function (i, item) { ...

Tips for implementing collapsible functionality that activates only when a specific row is clicked

I need to update the functionality so that when I click on a row icon, only that specific row collapses and displays its data. Currently, when I click on any row in the table, it expands all rows to display their content. {data.map((dataRow ...

Having trouble with installing angular-cli on a Windows 10 system connected to a proxy network

Attempting to setup angular-cli on Windows 10 while connected to a proxy network. Unfortunately, encountering errors when trying to install angular-cli on my machine. Specifically, receiving the following two errors in the command prompt ( 403 Forbidden - ...

Update the content of the text box when the button is clicked

How can I make the text box value appear only when a button is clicked? See the code snippet below: HTML: <input type="text" [(ngModel)]="serverName"> <button class="btn btn-primary" (click)="onAddClk">Add</button> TS File: onAddClk( ...

receiving a json object as opposed to a json array in php

Looking to get the output of json_encode() as an array, like so: [ { "url":"http://localhost/.....", "name":"abc" }, { "url":"http://localhost/.....", "name":"xyz" }, ] However, currently the result is in object format ...