Verify characteristics of recursive object within Angular 7

I have an object similar to the one in the stackblitz linked below and I need to determine if a key is of type Date. If it is, I want to add 3 days to that date. I have successfully implemented this for non-recursive objects, but I am facing challenges with recursive objects. How can I overcome this issue? Efficiency is crucial for me as my real-life objects are large and complex.

Check out the StackBlitz

  myObject = {
    aProperty: {
      aSetting1: 1,
      aSetting2: new Date(),
      aSetting3: 3,
      aSetting4: 4,
      aSetting5: 5
    },
    bProperty: {
      bSetting1: {
        bPropertySubSetting: new Date()
      },
      bSetting2: "bString"
    },
    cProperty: {
      cSetting: new Date()
    },
    dProperty: new Date()
  }


  convertButtonClick() {
    this.convert(this.myObject);
    console.log(this.myObject);
  }

  convert(obj) {
    for (var property in obj) {
      if (obj.hasOwnProperty(property)) {
        if (obj[property] instanceof Date) {
          obj[property].setDate(obj[property].getDate() + 3);
        }
      }
    }
  }

Answer №1

If you encounter an object property, you can use the convert function recursively to manipulate it:

function convert(obj) {
  for (let property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (obj[property] instanceof Date) {
        obj[property].setDate(obj[property].getDate() + 3);
      } else if (obj[property] instanceof Object) {
        convert(obj[property]);  // Recursive call
      }
    }
  }
}

Check out this stackblitz link for a demonstration.

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

Anticipating the outcome of a function in asynchronous JavaScript

After taking a break from web development for a couple of years, I recently dove back into it. While I dabbled in AngularJS before, I have now shifted my focus to Angular2. My current challenge revolves around handling asynchronous JavaScript. Despite enc ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

The parameter type 'DateInput' cannot be assigned to the parameter type 'Date'

I am currently utilizing fullcalendar for my project. However, I would like to utilize my local models instead of fullcalendar's model. The issue arises when attempting to create a new instance of my own model, as it displays the following error messa ...

Encountering an error when attempting to access an object property dynamically by using a passed down prop as a variable in Vue 2 & Vuex

I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed: Dynamically access object property using variable Dynamical ...

Puzzled by the specialized link feature

As I delve into the world of React and Next.js, I find myself working on the link component. Initially, I had a grasp on basic routing in next.js which seemed pretty straightforward. However, things took a confusing turn when I stumbled upon this code: imp ...

There was an error in processing node npm due to Z_DATA_ERROR with error code errno -3, indicating an

When attempting to run my TypeScript project using tsc, I encountered the following error: Found 181 errors in 4 files. Errors Files 1 node_modules/@types/eslint-scope/node_modules/@types/eslint/helpers.d.ts:1 1 node_modules/@types/eslint/hel ...

Ensuring that an interface exclusively contains properties from another interface

If I define an interface like this: interface Client { id: number; email: string; firstName: string; lastName: string; cellNumberFull: string; } Then, how can I create a new interface that includes only the properties from GoClient? interface ...

Tips for retrieving and storing an HTTP Post response in Angular 4 using HTML formatting

I am currently facing a challenge in Angular 4 where I am trying to retrieve and read the HTTP Post response. However, I am unable to do so because the response is in HTML format. Despite my efforts of researching various sources, I have not been able to f ...

Error message: The iOS system was unable to open the backing store due to a QuotaExceeded

Our Web-Application is quite large and is built on Angular with PWA capabilities enabled. Everything runs smoothly, including the offline mode functionality. We utilize PDFTron-Webviewer, which is cached by the Service-Worker to ensure availability in Off ...

Using Typescript to import functions

TLDR - I need help understanding the difference between these imports in ReactJs using Typescript: setState1: (numbers: number[]) => void, setState2: Function Hello everyone, I've encountered some strange behavior when importing functions with Typ ...

Angular menu with nested dropdowns

Is it possible to create a nested select menu similar to the example select screenshot menu below, using my mat-select? When a user selects an item from the REPM mat select, it should display the Master Broker Company menu on the right side. Thanks. #exam ...

The async pipe is failing to function properly when used with the same observable

I'm facing an issue with the async pipe in my view as it's not loading any data dynamically. On my page, I need to change observable values multiple times such as reloading the page, loading more values, and updating news content based on differ ...

The callback for the array change listener is not receiving any arguments

Recently, I've been pondering a way to manage change listeners for arrays without relying on Observables or external libraries. My approach involves using a .json file containing an array of objects (specifically of type Rent) as my database. The goa ...

Difficulty Aligning Angular Material Expansion Panel with mat-nav-listI am facing an issue with

Currently, I have implemented a mat-nav-list to showcase the Menu items on my webpage. However, there seems to be an alignment issue with the 4th Menu item which is an Angular Material Expansion control. Refer to the screenshot provided below for clarifica ...

What could be the reason that my Bootstrap dropdown menu is not appearing on my website

I am currently utilizing Angular in my project. I have incorporated bootstrap and jQuery via NPM install, and specified them as dependencies in angular.json. The navbar on my site contains a dropdown menu. When I hover over the dropdown menu, it should di ...

Problematic Component in Angular CLI 4.3.5 When Unit Testing with Karma/Jasmine

I am facing an issue with making the mock data function properly in order to create a new component. NullInjectorError: R3InjectorError(DynamicTestModule)[ListingsService -> AuthService -> MessageService -> MessageService]: import { ComponentFi ...

Top recommendation for updating NPM package within Angular 2

After integrating a 3rd party NPM package into my Angular 2 project, I found myself needing to make modifications directly within the node_modules directory. However, I am concerned that these changes will be lost once the application is deployed in a diff ...

The 'performance' property is absent in the 'FirebaseApp' type, which is necessary in the 'App' type

Encountering an issue during a fresh installation of Angular 7.2 and Firebase, specifically getting this error: ERROR in node_modules/@angular/fire/firebase.app.module.d.ts(17,22): error TS2420: Class 'FirebaseApp' incorrectly implements interfa ...

The returned type of intersected functions in Typescript does not match the inferred type

While attempting to extract the return type of an intersected request, I encountered a discrepancy between the return type and the inferred type. Check out the shortened URL for more details: https://tsplay.dev/mAxZZN export {} type Foo = (() => Promis ...

Pass information captured from Mat Dialog up to the main component

Looking for a way to pass true/false boolean data from a dialog box into the parent component without just console logging the result? You want to store it in a variable in the parent component for further use. Any suggestions on how to achieve this? This ...