Typescript - filtering out null values from JSON object

I am facing an issue with my service method that saves a date on the server. When this method sends the date to the server, it includes fields with null values in the JSON. How can I exclude these fields with null values?

public create<T>(post: any): Observable<T> {
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    };
    return this.httpClient
        .post<T>(`${this.url}`, JSON.stringify(post), httpOptions)
        .pipe(catchError((err, source) => this.responseHandler.onCatch(err, source)));
}

The JSON being sent to the server:

{
   "name": "test",
   "professionType":{
      "id": null
   },
   "comment": null,
   "organizationSpecialities":[
        {
         "speciality":{
            "id": null
         },
         "effective": 2,
         "effectiveDate":{
            "startDate": null,
            "endDate": "2019/12/01"
         }
      }
   ]
}

The desired JSON to be sent:

{
   "name": "test",
   "organizationSpecialities":[
         "effective": 2,
         "effectiveDate":{
            "endDate": "2019/12/01"
         }
      }
   ]
}

Answer №1

If you want to eliminate any null values or objects with no keys in a JSON object, you can achieve this by looping through the data and checking for these conditions.

Below is an example of how you can clean up your JSON data.

cleanseData(obj) {
  if (Object.prototype.toString.call(obj) == "[object Array]") {
    for (let index = 0; index < obj.length; index++) {
      this.cleanseData(obj[index]);
      if(Object.prototype.toString.call(obj[index]) == "[object Object]") {
        if(Object.keys(obj[index]).length === 0){
          obj.splice(index, 1);
          index--;
        }
      }

    }
  }
  else if (Object.prototype.toString.call(obj) == "[object Object]") {
    for (let key in obj) {
      let value = this.cleanseData(obj[key]);
      if (value === null) {
        delete obj[key];
      }
      if(Object.prototype.toString.call(obj[key]) == "[object Object]") {
        if(Object.keys(obj[key]).length === 0){
          delete obj[key];
        }
      }
      if(Object.prototype.toString.call(obj[key]) == "[object Array]") {
        if(obj[key].length === 0){
          delete obj[key];
        }
      }
    }
  }
  return obj;
}

You can also check out the code on StackBlitz for further reference.

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

Angular 6 - Separate whole numbers and decimal values to style them differently in CSS

Is there a way in Angular to format a price so that the cents/decimal part appears as a superscript? What would be the most effective approach in Angular to achieve this based on the initial setup below? export class PriceComponent implements OnInit { ...

Extracting JSON data from the DataFrame for analysis

I have some data stored in a column named 'data' in my dataframe as strings. I am trying to convert this data into JSON format using the command df['data'].to_json('data.json'). However, the output I am getting is showing esca ...

Using Vue's $set method to update nested JSON values

[ { "id": 1, "question": "Main Inquiry", "answers": [ {"id" : 1, "isSelected" : false}, {"id" : 2, "isSelected" : true}, {"id" : 3, "isSelected" : false}, {"id" : 4, "isSelected" : false}, {"id" : 5, "isSel ...

Leveraging JSON data in subsequent GET request in Ionic 3

My application receives input, concatenates it to a string, and then requests JSON data. The response includes the following first two lines: Now, I need to update my code to be asynchronous. It should make the initial call, wait for a response, retrieve ...

Converting a JavaScript object into JSON format

I am currently working on serializing a JavaScript object to JSON. Here is the code I have written so far: var info = {}; ... $.each(data, function (key, value) { info["name"] = value.name; info["id"] = value.id; ...

NX combined with Nest.js and TypeORM, further enhanced with Webpack and Migrations

Recently, I embarked on a project using NX (Nest.js + Angular) and set up TypeORM for database configuration. While everything runs smoothly in "serve" mode, I found myself struggling with configuring migrations. In a typical Nest.js project, all files in ...

Issue with Angular modal not opening as expected when triggered programmatically

I am working with the ng-bootstrap modal component import { NgbModal, ModalCloseReasons } from "@ng-bootstrap/ng-bootstrap"; When I click on a button, the modal opens as expected <button class="btn labelbtn accountbtn customnavbtn" ...

The initial processing step for the export namespace is to utilize the `@babel/plugin-proposal-export-namespace-from` plugin. Previous attempts to resolve this issue have been

I encountered a problem with my application and found two related questions on the same topic. However, due to a lack of reputation, I am unable to comment or ask questions there. That's why I'm reaching out here... Recently, I integrated Redux ...

Exploring Angular 2's Routing Features Across Different Cultures

Looking to integrate culture into all routes in my application utilizing RC4. How can I adjust the existing routes to achieve this objective? export const routes: RouterConfig = [ ...ItemRoutes, ...LibraryRoutes, { path: '', redirectTo: 'd ...

Ensure that Angular CLI libraries contain all necessary dependencies

I'm currently facing a challenge with integrating Angular Material dependency into my custom library. The main application that references the custom library encounters an error stating "Cannot find @angular/material/core" and "@angular/material/tabs" ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

The zip() operator in RxJS is not functioning as intended. It consistently finishes execution without emitting any values

Suppose you have an observable containing a large number of elements, say 450 or more. You want to transfer these elements to a different observable in batches of 100 elements each. You can check out a functional example provided by @martin at this link: ...

How can HostBinding be used to target a custom directive in order to deliver either a success or error message and show it on

I am incorporating a custom directive to display specific server messages/errors following an http request. For example, in the response or error section, I want to target the custom directive and present the emphasized message. The directive is already e ...

PHP Form Submission: A Simple Guide

One scenario that I'm facing is using the submit button event to populate a field in my form with a value. However, now I'm having trouble getting the form to submit at the same time. Any suggestions on what I can do? Check out this link for mor ...

What is the best way to verify the JSON request in a Spring Boot application?

I need to verify the JSON request I receive from the client side. Despite successfully using annotations like @notnull and @length(min=1,max=8), I am struggling to access the specific fields and error messages that are triggered when validation fails. Alth ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Struggling with testing the checkbox when it changes inside the CardHeader Avatar={} component

I've recently implemented a feature similar to the example showcased on MaterialUI's TransferList. However, I'm encountering difficulties accessing a checkbox within the avatar={}. The project utilizes Jest and Enzyme for testing purposes. T ...

Encountered difficulties when trying to incorporate SCSS into my rollup build

Desired Outcome I aim to develop a small library for personal use, focusing on separating code into library (product) and application (project) code. All my source code resides in the /src folder, consisting of React, TypeScript, and SCSS code. I would l ...

Leveraging the power of the Async pipe within an Angular TypeScript file

Using the async pipe in HTML involves utilizing the syntax "Products$ | async as products". But can we also access these same products in the TypeScript file? Is this possible? ...

Displaying HTML content in Angular 15

Struggling with Angular 15.2, I'm attempting to develop a component that can render valid HTML input. My initial approach involved using ElementRef and innerHTML: constructor( private readonly componentElement: ElementRef, ) {} ngOnInit(): void { ...