How to efficiently eliminate null values from JSON objects in Angular

Can you help me troubleshoot an issue with removing null values from a JSON object before making a post request? The code snippet I provided below isn't achieving the desired outcome. Any insights or suggestions would be much appreciated.

publish() {
    let resource = JSON.stringify(this.form.value)
        const removeEmpty = (obj) => {
      Object.keys(obj).forEach(key => {
         if (obj[key] && typeof obj[key] === "object") {
           removeEmpty(obj[key]);
         } else if (obj[key] === null) {
           delete obj[key];
         }
       });
       return obj;
    };
    console.log("new obj :" + removeEmpty(resource));
}

Check out the Stackblitz for a sample example

Answer №1

Your data is currently in string format due to the use of stringify on your object. It would be best to remove the stringify method.

publish() {
    let data = this.form.value;
        const cleanUp = (obj) => {
      Object.keys(obj).forEach(key => {
         if (obj[key] && typeof obj[key] === "object") {
           cleanUp(obj[key]);
         } else if (obj[key] === null) {
           delete obj[key];
         }
       });
       return obj;
    };
    console.log("cleaned up object :", cleanUp(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

Creating a JSON object from a PHP MySQL query result

I am delving into the world of cordova in order to create a practice android app. This app is designed to display data on a chart. The x axis represents dateTime values, while the y axis displays Energy values. Although I understand this might seem like a ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

Trying out the combination of @inject parent and @contentChildren in practice

I have been working on developing a unique custom tab component that consists of both parent and children elements structured as follows: Parent @Component({ selector: 'app-custom-tabs', template: ` <div class="inline-flex"> ...

The NetSuite https.post() method is throwing an error that reads "Encountered unexpected character while parsing value: S. Path '', line 0, position 0"

I'm currently facing an issue when trying to send the JSON data request below to a 3rd party system using the "N/https" modules https.post() method. Upon sending the request, I receive a Response Code of "200" along with the Error Message "Unexpected ...

Steps to save JSON response within WCF on a service level

I have a WCF service that sends JSON data to clients. Here is the configuration in the app.config file: <system.serviceModel> <services> <service name="MyServices.MyService"> <endpoint address="" behaviorConfiguration="JsonBe ...

How to load vector tiles from a binary file using OpenLayers

I'm attempting to load a vector tile in binary format into OpenLayers but I'm facing challenges with the tileLoadFunction. I'm struggling to manually set the data to the tile. The reason why I need to use the tileLoadFunction is because I ha ...

Real-time JSON Data Retrieval Using Ajax jQuery and Google Sheet API

Seeking a live data search tool that works with JSON spreadsheets Check out this link for more information name = data.feed.entry[i]['gsx$name']['$t']; img = data.feed.entry[i]['gsx$img']['$t']; price ...

Exploring JSON arrays with HiveSQL

In my Hive table, I am working with data generated from reading a Sequence File in the HDFS. These sequence files are formatted as JSON and resemble the following: {"Activity":"Started","CustomerName":"CustomerName3","DeviceID":"StationRoboter","OrderID ...

Pausing or buffering an RxJS 6 observable when the page is inactive

Currently, I am dealing with a stream of letters that need to be arranged in the correct order to form a word. However, an issue arises when the user switches tabs, minimizes the browser, or switches applications - the behavior mimics using setTimeout(), r ...

Inject data into an Angular 2 template

Does anybody know of a method to pass variables to templates in Angular2? Suppose I have the following code snippet: <div *ngFor="foo in foos"> <ng-container *ngTemplateOutlet="inner"</ng-container> </div> --------------- <n ...

An issue has arisen within the template of the Angular component RegisterComponent

Error Message: Angular Register Component Issues When using the Angular Register component for user registration, the register.component.html file shows the following code: <div class="form-group"> <label for="name" ...

Can you guide me on how to record a value in Pulumi?

According to Pulumi's guidance on inputs and outputs, I am trying to use console.log() to output a string value. console.log( `>>> masterUsername`, rdsCluster.masterUsername.apply((v) => `swag${v}swag`) ); This code snippet returns: & ...

Tips for locating elements within an array of objects in JSON

I am working on implementing a search filter for accordion data that should be able to search within the title and contents, including the 'name' key. Currently, I have a function in place to perform this search, but it does not cover searching ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

Validation failed for the WebAPI OData request, and the ModelState object was not returned

I am currently developing an AngularJS web form to execute a POST request (insert) into a table utilizing WebAPI configured as OData. My objective is to receive a failed validation ModelState object back in JSON format, so I can validate the appropriate fi ...

Using Node.js to insert a new element into a JSON array

I am working with a JSON array [{id:1,data:"test1"},{id:2,data:"test2"}] My goal is to add a new element to each object in the array based on the value of the "data" field. For example, if the data value is "test1", ...

Converting JAX-RS/JAXB JSON to POJO will only map fields that exist in both the JSON and the POJO, ignoring any additional fields present

In the process of developing an API that must support JSON payloads for PUT/POST requests, which may contain additional fields beyond what is defined in the known POJO. For instance: @XmlRootElement public FruitCounter { int numberOfApples; int num ...

Error: Trying to access a property of an undefined variable (retrieving 'x')

As a newcomer to the MEAN stack, I am attempting to create some basic posts. However, I keep encountering an error that reads TypeError: Cannot read properties of undefined (reading 'title') when trying to issue a post. The strange thing is, when ...

Guide on inserting a template into mat-stepper

My goal is to achieve the following: <ng-template #content> <mat-step>step 1</mat-step> <mat-step>step 2</mat-step> </ng-template> <mat-horizontal-stepper> <ng-container *ngTemplateOutlet="content">&l ...

A guide to testing the mui Modal onClose method

When using material UI (mui), the Modal component includes an onClose property, which triggers a callback when the component requests to be closed. This allows users to close the modal by clicking outside of its area. <Modal open={open} onCl ...