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

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Separate a set of HTML elements with specific heights into individual page divisions

The current method in place is quite average: Prior knowledge of each object's height is required. We possess a set of such objects that could potentially be separated by a page break. We start with a blank slate and insert an opening <div class= ...

What is the process of converting PHP to JSON?

Is it possible to convert PHP code into JSON format? I am a beginner in PHP coding and looking to learn more about it as I integrate it into my Android application. I am also curious about how to display the information visually. For example, I would like ...

Angular 2: Changing the name of a component

Looking for guidance on renaming a component in my Angular2 application. I've already updated all the necessary files - changed the file names and folder name, as well as made adjustments to specific files such as y.component.ts, app.routing.ts, and a ...

Is it possible for jQuery UI Dialog to function similar to an iFrame?

Is there a way to set up my dialog box with a form so that when the form is submitted, only the dialog box changes instead of the browser location? ...

JavaScript function for submitting form data using AJAX and performing validation

This is the code I have been working on: $(function () { $('.contact-form').submit(function (event) { $(this).find("input , textarea").each(function () { var input = $(this); if (input.val() == "") { ...

Sending information from a controller to a view in Ruby: a how-to guide

Currently, I am utilizing Ruby and facing the need to provide users with a constant status update message while a lengthy task is executed in the controller. During this method, various rows are being inserted into the database. My goal is to display a me ...

Issue with App.Module imports not functioning properly on Ionic pages

I am currently working on a directive that I want to implement in my pages. However, when I import something into app.module, it seems as though the pages are not considered children of app.module. On the other hand, if I directly import the directive into ...

What is the best way to use createElement in JavaScript to insert <p> and <span> elements within a <div>?

I am currently experimenting with generating sentences accompanied by draggable text boxes. To achieve this, I intend to construct the following HTML structure using JavaScript exclusively: <div> <p>Data1<span class = "smallBox droppabl ...

Tips to avoid unauthorized use of permissions post-logout

I recently encountered an issue with my C# project that involves administrative functions accessible through a login screen. During a security test, we discovered a vulnerability where if a user submits a form, logs out, and then repeats the form post usi ...

Difficulty encountered in generating an array of JSON entities

So, I am tasked with creating an array of JSON objects in a specific format: [object, object, object...] To achieve this, I iterate through all the selected rows in my jQuery jtable, consolidating all parameters for each row into a single object. After r ...

Is it possible to add and delete DIVs simply by clicking on a link?

By utilizing a select dropdown list and appending the HTML code stored in the variable "code" (resembling <div>...</div>) right before the end of the div with ID mydiv using $(code).appendTo('#mydiv');. Within these dynamically added ...

The API mistakenly inserts multiple entries instead of just one

Recently, I upgraded to mvc net core 3.0 from net core 2.2 and encountered a strange issue. Every time I attempt to add a new record to the database, the application ends up creating 9 copies of the same record in the DB. This occurs across all tables in m ...

Tips on modifying the maxlength attributes for all "field answer" class elements

Looking for some help with adjusting the "maxlength" attribute in a class called "field answer." The current maxlength is set to 250, but I need it changed to 9999. Can someone guide me through this process? <div class="field answer"> &l ...

React TypeScript with ForwardRef feature is causing an error: Property 'ref' is not found in type 'IntrinsicAttributes'

After spending a considerable amount of time grappling with typings and forwardRefs in React and TypeScript, I am really hoping someone can help clarify things for me. I am currently working on a DataList component that consists of three main parts: A Co ...

Error when attempting to add data into MongoDB using Node.JS: "The type 'string' cannot be assigned to type 'ObjectId | undefined'."

Attempting to add a document to the collection results in an error when specifying the _id field of the added document. How can I insert a document with an _id that is not an ObjectId? The error occurs with the following code. Omitting the _id resolves th ...

Choosing arbitrary data points from a JSON document

I've been working on a program to randomly pick and display questions from a list stored in a `.json` file. Here's the current code I have: import json import random with open("C:\\LearningArabic\\LiblibArriby\\Les ...

Develop a cutting-edge Drag and Drop Functionality using the innovative Material CDK

Here is a unique link you can check out: https://stackblitz.com/angular/nabbkobrxrn?file=src/app/cdk-drag-drop-enter-predicate-example.ts. In this example, I have specific goals: I want to be able to select only one number from the "Available numbers" l ...

Tips on how to showcase up to 200 characters from a string

<?php include ($_SERVER['DOCUMENT_ROOT'].'/header.php'); include ($_SERVER['DOCUMENT_ROOT'].'/adtop.php'); if(mysql_num_rows($deals) > 0){ while($row = mysql_fetch_assoc($deals)){ echo '<div id= ...

Exploring the potential of the forkJoin operator in Angular 4's Observable

I'm currently facing a challenge that involves retrieving both administrators and professionals from the "users" collection using AngularFire's latest version. I am utilizing Observables for this task. My goal is to make two parallel requests an ...