Elimination of any null value fields upon form submission in Angular 2

Hey everyone, I'm currently working on a project that uses a Model driven form. When I submit the form, I am encountering an issue where I get null values in my formGroupObj.value. I need to find a way to remove fields with null values.

Here is how the current output looks:

{
   "firstName":"Jack",
   "lastName":"M",
   "age":null
}

What I'm expecting as output is:

 {
    "firstName":"Jack",
    "lastName":"M"
 }

Does anyone know of a default way to achieve this desired output?

I would really appreciate any help on this issue. Thank you!

Answer №1

let person = {
   "name":"Sarah",
   "last":"Doe",
   "age":null,
   "otherValue": null
};

Object.keys(person).forEach((key) => (person[key] == null) && delete person[key]);
console.log(person);

Answer №2

let person = {
   "name":"Sarah",
   "age":25,
   "job": null,
   "hobby": null
};

for(key in person) {
  if(person[key] === null) {
    delete person[key];
  }
}

console.log(person);

Answer №3

When dealing with nested objects, particularly nested Form Groups, a recursive function is necessary:

const data = {
  "name": {
    "firstName":"Alice",
    "lastName": null,
  },
  "age":null,
  "address": "123 Main St"
};

const removeNullValues = (data) => {
  Object.keys(data).forEach(key => {
     if (data[key] && typeof data[key] === "object") {
       // recursion
       removeNullValues(data[key]);
     } else if (data[key] === null) {
       delete data[key];
     }
   });
};

removeNullValues(data);

Output:

const newData = {
  "name": {
    "firstName":"Alice",
  },
  "address": "123 Main St"
};

Live Example: https://jsfiddle.net/yv9tg8zp/

Answer №4

After reviewing andreivictor's response, I made enhancements to eliminate empty FormGroups as well.

cleanseEmpty = (data: any) => {
  Object.keys(data).forEach((key) => {
    // recursive for FormGroups
    if (data[key] && typeof data[key] === 'object') this.cleanseEmpty(data[key]);
    // check for null values
    if (data[key] === null) delete data[key];
    // remove empty objects (empty FormGroups)
    if (JSON.stringify(data[key]) === '{}') delete data[key];
  });
  return data;
};

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

Strategies for implementing classes in Typescript

I've been working on incorporating more classes into my project, and I recently created an interface and class for a model: export interface IIndexClient { id?: number; name?: string; user_id?: number; location_id?: number; mindbody_id?: nu ...

Encountering a type error when attempting to filter TypeORM 0.3.5 by an enum column that is

I have the following configuration: export enum TestEnum { A = 'A', B = 'B' C = 'C' } @Entity() export class User { @PrimaryGeneratedColumn() id: number @Column({enum: TestEnum}) test: TestEnum } ...

Steps for implementing an onclick action in Angular 4 from infowindow content

Currently, I am integrating Google Maps into an Angular 4 project and I need to implement a click event inside the infowindow. How can I achieve this? I attempted the following code but encountered an issue where the name is undefined. Even though I called ...

Modify the System.config() in Angular 2 following the segregation of JavaScript and TypeScript files

My project follows the folder structure of quick-start ToH, which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt1.html In order to separate the .ts and .js files, I included the following line in the tsconfig.json file: "outDir": "dist" ...

Unable to retrieve headers from extended Express.Request type

Currently, I am attempting to enhance the Request in Express so that it accurately represents the structure of a query. My current approach is as follows: export interface TypedRequestQuery<T> extends Express.Request { query: T; } While this met ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

Adding a custom button to CkEditor 5 in Angular 12: Step by step tutorial

How can I customize the toolbar in version 4 of Ckeditor 5 by adding a unique button? I have tried looking through the documentation, but have been unsuccessful in achieving my goal. ...

Creating rectangular shapes on the canvas with the help of react hooks

I have a React+Typescript web application and I am currently working on implementing the functionality to draw rectangles on a canvas. My goal is to utilize React hooks instead of classes in order to achieve this. The desired outcome is to enable the user ...

Tips for implementing ID enforcement on downgraded Angular 2+ component

Currently in the process of transitioning AngularJS 1.6 components to Angular 4.3.2, I encountered a need to implement an id attribute on the component tag. However, in order to integrate ng2+ with existing ng1 components, downgrading is required: angular ...

The feature of using a custom find command in Cypress does not support chaining

I am interested in developing a customized Cypress find command that can make use of a data-test attribute. cypress/support/index.ts declare global { namespace Cypress { interface Chainable { /** * Creating a custom command to locate a ...

Trouble with 'import type' declaration causing build issues in a Next.js project

Having trouble importing the Metadata type from the next module. The code snippet below is directly from the Next.js documentation. THE ISSUE client.js:1 ./app/layout.tsx:3:12 Syntax error: Unexpected token, expected "from" 1 | import React from 'r ...

When inserting a child element before the myArray.map(x => ) function, it results in rendering only a single child element from the array

Sorry for the confusion in my explanation, but I'm encountering an issue with displaying elements from an array. Here is the code snippet I am working on. Currently, the myArray contains 10 elements. When I place the <LeadingChild/> component ...

What methods does the TypeScript compiler use to locate npm packages containing types?

When configuring the typescript compiler, you can utilize the tsconfig.json file. This will also give you access to options for finding type definition files using the typeRoots key. By default: All visible "@types" packages are automatically included in ...

I recently updated Angular Cli and now my app is searching for node_modules in a different location. Is there a way for me to revert it

Current Versions. @angular/cli: 1.4.2 node: 6.10.0 os: linux x64 @angular/animations: 4.3.6 @angular/common: 4.3.6 @angular/compiler: 4.3.6 @angular/compiler-cli: 4.3.6 @angular/core: 4.3.6 @angular/forms: 4.3.6 @angular/http: 4.3.6 @angular/platform-brow ...

Angular2 Window Opener

Trying to establish communication between a child window and parent window in Angular 2, but I'm stuck on how to utilize window.opener for passing a parameter to Angular 2. In my previous experience with Angular 1.5, I referenced something similar he ...

Exploring Angular2's DOMContentLoaded Event and Lifecycle Hook

Currently, I am utilizing Angular 2 (TS) and in need of some assistance: constructor(public element:ElementRef){} ngOnInit(){ this.DOMready() } DOMready() { if (this.element) { let testPosition = this.elemen ...

Passing Imported Module to Feature Module in Angular 7

In my Angular 7 app, I have set up a hierarchy of feature modules. The structure looks like this: app admin (UI module imported here) feature1 feature2 public Within the admin module, I have included a UI framework module. My question is, if modules ...

Number that is not zero in TypeScript

Trying to find a solution in TypeScript for defining a type that represents a non-zero number: type Task = { id: number }; const task: Task = { id: 5 }; const tasks: { [taskId: number]: Task } = { 5: task }; function getTask(taskId: number | undefined): T ...

Custom error handlers are never triggered by Angular 2 errors

I'm facing an issue with my Angular custom error handler implementation (v2.4.3). Even though I have a simple setup, the errors are not being logged. What could be causing this problem? app.module.ts providers: [ { provide: ErrorHandler, useClas ...

What steps can I take to fix the ESM / require error while using TypeScript 4.8?

My Node.js application uses TS 4.8, and I recently updated the file-type package. However, after the update, my project compilation fails with the following error: [1] const _fileType = /#PURE/ _interopRequireWildcard(require("file-type")); [1] ...