Convert TypeScript model to JSON while excluding properties with null values

When working with an Angular 4 App and a typescript model, I have defined a Person class as follows:

export class Person{
  fname:string,
  lname?:string
}

The 'lname' property in the model is optional. To populate the model in a component, I use the following code:

//Query form data
var people = form.get('people');

let model = new Person(){
  fname: people.get('firstname'),
  lname: people.get('lastname')
}

In this scenario, if the user does not enter a value for 'lastname', the resulting JSON will include a null value for 'lname':

 {'fname': 'xyz', 'lname': null}

Expected Result:

To avoid having null properties in the JSON output, I want it to look like this:

 {'fname':'xyz'}

However, when the user does enter a value for 'lname', the JSON should include both values:

{'fname':'xyx', 'lname': 'abc'}

I am looking for a way to achieve this desired JSON result from my TypeScript model.

Answer №1

Before adding any value, make sure to review the content of the lastname property in your form. Only proceed with inserting the value if it is a string.

Here's an example code snippet for reference:

// Accessing form data
var people = form.get('people');

const personModel = new Person();
personModel.fname = people.get('firstname');
if (typeof people.get('lastname') === 'string') {
  model.lname = people.get('lastname');
}

Answer №2

Check out this useful library I made that might be of assistance to you. https://www.npmjs.com/package/ngx-super-model

By employing the clean() method on an object that inherits from the Model class, you can eliminate any null, undefined, or NaN values.

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 could be causing the Ajax http get request to not be retrieving the JSON data as expected?

I am facing an issue with retrieving JSON or HTML from my MVC controller using an Ajax call. The problem arises when trying to make a GET request instead of a POST request. $.ajax({ url: url, type: "POST", //It works but doesn't work with GET ...

How can I use jQuery to reposition an inner element to the front?

Imagine you have a collection of elements: <ul id="ImportantNumbers"> <li id="one"></li> <li id="two"></li> <li id="topNumber"></li> <li id="four"></li> </ul> Every five seconds, the ...

Using Angular to handle routes with a specific domain prefix

Let's say I own the domain https://example.com and I'd like to create a subdomain specifically for my blog, like this: https://blog.example.com. How would you handle the routing for this scenario using Angular? ...

The term 'Employee' is typically used as a classification, but in this context, it is being treated as a specific value

I am encountering an issue while trying to define a variable as type Employee. The error message 'Employee' only refers to a type but is being used as a value here. ts(2693) keeps appearing. Here is my show-api.ts code: import { Component, OnIni ...

Automatically update the cart count in the header component in Angular 6 when a product is added to the cart, without the need to

I am working on an E-Commerce application using Angular 6. I am facing an issue with updating the shopping cart count in the header component whenever a product is added or removed from the cart. The cart count only updates when I refresh the page. I have ...

Pause the jquery script when a key is pressed

Currently, I have a script that loads a php file within a div and automatically refreshes every 5 seconds. Check out the code below: $("#load_timeout").load("time_out.php"); var refreshId = setInterval(function() { $("#load_timeout").load('time_o ...

Access the Angular element in the view with jQuery

I'm fairly new to Angular and I have a feeling that there's a concept I'm not quite getting. Here's what I'm trying to achieve: I want to load the main view, then click a button on the main view to load a different view. Once the ...

Generating auto UUIDs in PostgreSQL using TypeORM

Currently, I am in the process of developing a REST API and utilizing TypeORM for data access. While I have been able to use it successfully so far, I am facing an issue regarding setting up a UUID auto-generated primary key on one of my tables. If anyone ...

Updating a JSON array by including a new key-value pair using Javascript

Below is a json string that needs to be converted into a new Json Array: Raw Data: [ ["yrxqBHmPkNhZ60_eab97ebf-c2a3-40a5-972a-91597ad9a4ca_99371", "SUCCEEDED", "2023-08-31T21:59:31.325000+05:30", "2023-08-31T22:13:42.165000+05:30"], ["yrxqBHmPkNhZ ...

Utilizing a combination of a `for` loop and `setInterval

I've been encountering an issue for the past 3-4 hours and have sought solutions in various places like here, here, here, etc... However, I am unable to get it to work in my specific case: var timer_slideshow = {}; var that, that_boss, has_auto, el ...

What is the best way to iterate through all values in a LinkedTreeMap with the keys as Strings and the values as

I am facing an issue where I have a JSON file and all the data is stored in a LinkedTreeMap<String, Object>. The problem arises when one of the JSON fields becomes complex: { "val1": "1", "val2": "2", "val3": { "embVal1": "emb1", ...

Nest may struggle with resolving dependencies at times, but rest assured they are indeed present

I've encountered a strange issue. Nest is flagging a missing dependency in a service, but only when that service is Injected by multiple other services. cleaning.module.ts @Module({ imports: [ //Just a few repos ], providers: [ ServicesService, ...

Is there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...

Having trouble extracting information from a JSON link to populate an Angular Material Table

I have successfully implemented the Angular Material Table to display data from a List. Now, I want to fetch data from a JSON URL and populate this list with that data. I've attempted several methods found online to parse the data into the list, but ...

Dynamic Image Grid Created Using JavaScript Glitches

My dilemma involves using JQuery to create an HTML grid of images styled with Flex Boxes. The setup works perfectly on desktop, but when viewing it on mobile devices, the images begin to act strangely - jumping, overlapping, and even repeating themselves i ...

What is the process of nesting widgets in kendoui with the PHP wrapper?

I have created a code using treeview in manual mode. div id="treview-back"> <?php $treeview = new \Kendo\UI\TreeView('treeview'); // function to create TreeViewItem with imageUrl function ImageTreeViewItem($text) { ...

Having trouble with CSS Locator identifying an element in your Protractor Test?

In the Protractor test snippet below, I am attempting to calculate the quantity of div elements using the CSS locator: let list = element.all(by.css('div[class="ag-header-cell ag-header-cell-sortable"]')); expect(list.count()).toBe(11); ...

Retrieving information selectively using useSWRImmutable

Having issues fetching data using useSWRImmutable. The problem arises when attempting to display the fetched data inside the UserRow component. Even though I can successfully print the data outside of the UserRow component, any console.log() statements wi ...

What Causes a Mongoose Query to Result in an Empty Array?

Hello, I have reviewed similar questions regarding the issue I am facing with developing an API. Despite trying different solutions, none seem to resolve my problem. When handling request and response payloads in my API, everything seems to be working fin ...

Unable to upload the file using AJAX

Here is my AJAX request where I am attempting to send form data to a PHP page and display messages accordingly. The problem I'm encountering is that when using serialize() method in AJAX, my file data is not being posted. As a result, the send.php scr ...