If all elements within the object are null, return true. Additionally, there will be another nested object within the main object

Need a universal solution to eliminate empty rows from an object.

The object contains a list of properties.

Here is a sample object that needs checking:


{
  "test": {
    "id": null
  },
  "testName": null,
  "specimen": {
    "id": null
  },
  "specimenName": null,
  "collectionDate": null,
  "resultDate": null,
  "result": null,
  "finding": null,
  "resultValue": null
}

Previous attempts failed, especially when there are lists inside the object.


purgeEmptyRows(obj: any): boolean {
  let isEmpty = false;
  Object.keys(obj).forEach(key => {
      if (!obj[key]) {
          isEmpty = false;
      } else {
        return true;
      }
  })
 return isEmpty;
}

Answer №1

Give this a try:

this.modifyValues(obj, null, []);    

modifyValues(obj: any, value: any, newValue: any) {           
    for (var x in obj) {
        if (obj.hasOwnProperty(x)) {
            if (typeof obj[x] == 'object') {
                this.modifyValues(obj[x], value, newValue);
            }
            if (obj[x] == value) { 
                obj[x] = newValue;
                // break; // uncomment to stop after first replacement
            }
        }
    }
    console.log(JSON.stringify(obj));
}

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

Exploring limitless possibilities with Vue slot manipulation

Imagine I am looking to develop a multi-layered Component for reusability, similar to a 'Tab' UI. This would allow developers to use it like this: <tabs> <tab label="My First Tab"> Content for first tab which could co ...

Best practices for defining TypeScript types

In my quest to optimize my TypeScript type definitions, I have scoured countless pages for the best approach. In the past, I kept a typings.ts file tucked away in my project, importing types into each file as needed using: import {IMyCustomType} from &a ...

Modify the innerHTML to adjust font size when a button is clicked in Ionic 5, or eliminate any unnecessary spaces

I have been experimenting with changing the font size of a variable in .html when the variable contains whitespace. In my .ts page, I use the following code to remove the whitespace: this.contents = this.sanitizer.bypassSecurityTrustHtml(this.product[&apos ...

How to Modify CSS in Angular 6 for Another Element in ngFor Loop Using Renderer2

I have utilized ngFor to add columns to a table. When a user clicks on a <td>, it triggers a Dialog box to open and return certain values. Using Renderer2, I change the background-color of the selected <td>. Now, based on these returned values, ...

Adding Crypto-JS to an Angular 2 application

For my Angular 2 development using TypeScript and SystemJS, I needed to integrate crypto-js. Here is the configuration in my systemjs.config.js file: (function (global) { System.config({ paths: { 'npm:': 'node_modules/' ...

Exploring the communication between two components in Angular 2

My Angular components include: Create-Articles: used for creating articles. List Articles: utilized for listing all articles. The parent component is the Home Component. import { Component, OnInit } from '@angular/core'; @Component({ ...

Unable to create canvas drawings using fingertips on mobile web browsers

Check out the code snippet below: canvas = document.getElementById("canvas"); ctx = canvas.getContext('2d'); tmp_ctx = element[0].getContext('2d'); element.bind('mousemove touchmove', function(event){ if(draw ...

Issue: Unable to locate the module 'nexmo' & error TS2307: 'nexmo' module not found

Currently, I am utilizing the powerful NestJs Framework alongside typescript. My task involves incorporating two-factor authentication (SMS) using the Nexmo node library. You can find further information on their website: During the development phase, ev ...

Tips for extracting the decimal portion of a floating point number in TypeScript

Is there a way to retrieve the number that comes after the decimal point in a float number using TypeScript? For example, in the number 2.3, I would like to obtain a return of 3. ...

Meteor does not react to updates from PHP7 on MongoDB, but it does react to updates from the MongoDB terminal

I am setting up the following configuration Meteor 192.168.0.53:3000 Mongodb 192.168.0.53:27017 Php7 /update.php 192.168.0.51 Php7 /show-live-update.html 192.168.0.51 A) In order to run this example successfully, ensure that show-live-update.html (192 ...

Adding extra fields to an existing JSON response in a TypeScript REST API

I am in need of an additional column to be added to my response data. Currently, I am fetching data from multiple REST endpoints one by one and merging the results into a single JSON format to display them in an Angular Mat table. The columns that I want t ...

To prevent duplicate values in the array, do not increment the count if the item is already present

I am facing an issue with incrementing items in my mongodb using find $in array. In cases where there are identical items in an array, such as ['apple','apple'], the item should be incremented twice. However, in my current scenario, it ...

Testing Angular applications using Jasmine

Looking to set up some Jasmine tests for a web application. How can I test content insertion from the page? For example, when testing the controller with mocked data, the sum function works fine. However, when testing on the actual page, it throws an erro ...

What is the best way to utilize ngStyle in combination with Interpolation?

Within my application, I am faced with a challenge involving two slide bars that generate values ranging from 1 to 100. Based on these generated values, I aim to adjust the margin of a div element in accordance with the percentage output. Despite conductin ...

The behavior of comparing variables in Javascript

Encountering an unusual issue while attempting to compare two strings using regex. Even after comparing both variables in the watch, the result remains the same. Seeking assistance in identifying the cause. Below is my code and also an image showcasing the ...

Handling errors in nested Promises and rxjs Observables in Angular 12 with Typescript and rxjs

My current code involves a mix of nested Promises and subscriptions, but all I want to do is this: Call my function bar() and determine if it executed successfully or encountered an error Current approach: Currently, my bar() function returns a boolean O ...

AngularJS - Component that allows access to a text value

There is an issue with my service where it doesn't update the exposed string value externally. The service itself knows that the value has changed, but externally it remains the same. When I try nesting the string inside an object, it works fine, but ...

Transmit the Angular data model to the server

Whenever any of the inputs change, this function is triggered: $scope.updateOutputData = function(){ // Collecting input data and creating object $scope.selectionObject = { "departure_city" : departureCityDigest, "departure_country" : ...

It appears that you are currently utilizing legacy implementation in your code. To ensure optimal performance, we recommend updating your code by incorporating createWrapper() and wrapper.useWrappedStore()

I am encountering an issue while using redux toolkit with Next.js. I am receiving the following legacy warning- /!\ You are using a legacy implementation. Please update your code: use createWrapper() and wrapper.useWrappedStore(). I am unsure of whe ...

The immutability of TypeScript's `as const` compared to JavaScript's Map object

Let's delve into a straightforward example: const simpleObject = { one: 'one', two: 'two', three: 'three' } Historically, pre ES2015 objects did not guarantee the preservation of key order upon retrieval. However, ...