Exploring through objects extensively and expanding all their values within Angular

I am in need of searching for a specific value within an object graph. Once this value is found, I want to set the 'expanded' property to true on that particular object, as well as on all containing objects up the object graph.

For example, given the following data:

`regions: [
{ id: 1, name: 'Canada Mock', code: 'CA', bulk: '', expanded: false, subRegions: [] },
{ id: 2, name: 'Mexico', code: 'MX', bulk: '', expanded: false, subRegions: [] },
{
  id: 2, name: 'United States region', code: 'US', bulk: '', expanded: false, subRegions: [
    {
      id: 1, name: 'US sub region', countries: [
        {id: 1, name: 'Saint Vincent and the Grenadines', code:'SV', states:[]},
        {id: 2, name: 'Trinidad and Tobago', code:'TR', states:[]},
        {
          id: 3, name: 'United States', code:'US', states: [
            { id: 1, name: 'Alabama', code: 'AL', expanded: false, cities: [] },
            ...
                    ]
                },
                ...
        }
      ]
    }
  ]
}
]`

If I were to search for 'LGA', the path leading to it would be expanded as follows: 'United States region'->'US sub region'->'United States'->'New York'->'New York City'

Answer №1

Figured it out by myself:

locateValueNode(target){
  this.expandIfNecessary(this.info, target, ["categories", "subCategories","items"])
}

expandIfNecessary(currentNode, target:string, childProperties:string[]){
  if(currentNode.id === target){
     currentNode.opened = true;
     return true;
  }
  let located:boolean = false
  let childProperty = childProperties[0];
  let subNode = currentNode[childProperty];
  
  if(subNode)
    subNode.forEach(item => {
      if(this.expandIfNecessary(item, target, childProperties.slice(1)))
      {
        currentNode.opened = true;
        located = true;
      }

  })
  return located;
}

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

Issue with Symbol Constructor in Typescript: [ts] The 'new' keyword can only be used with a void function

Just starting out with typescript and experimenting with the ES6 Symbol constructor. How can I address this ts lint problem without resorting to using any? const symbol = new Symbol(path); I'm trying to avoid doing this: const symbo ...

Prevent the Icon in Material UI from simultaneously changing

I'm working on a table where clicking one icon changes all icons in the list to a different icon. However, I want to prevent them from changing simultaneously. Any suggestions on how to tackle this issue? Code: import React from 'react'; im ...

Angular relative routes are failing to function

I am currently working on implementing a feature module in my project and following the documentation provided. My crisis-routing.module file looks like this: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from ' ...

Exploring PHP's SimpleXML searching capability

In my PHP script, I have a SimpleXML variable that contains an XML file. From this XML file, I need to locate the status and unit_id of one of the bin children. Although I know which shelve[] child the information will be under, I do not know the specific ...

Tips for retrieving JSON files within karma tests

I am currently working on developing a test for my TypeScript class that involves retrieving data from a JSON file. readData<T>(filePath: string): Promise<T> { return Qajax.getJSON(filePath); } For testing purposes, I am utilizing the Jas ...

What is the process for implementing custom color props with Material-UI v5 in a React TypeScript project?

Looking to enhance the MUI Button component by adding custom color props values? I tried following a guide at , but encountered errors when trying to implement it in a custom component. The custom properties created in createPalette.d.ts did not work as ex ...

Experiencing unexpected behavior with Next.JS getStaticProps functionality

I am currently working on a website where I want to display dynamic feedback as cards. However, my fetchData variable within the Home function is always returning undefined. Here's the code snippet I have tried: import UserCard from "../component ...

Is there a way to target the mat-icon element using the icon's name in CSS

I have a group of mat-icons that are automatically generated, meaning I cannot assign them ids or classes. The only way to distinguish between them is by their names: <mat-icon role="img">details</mat-icon> <mat-icon role="img ...

Creating a simulated provider class to simulate a response and manage promises - Implementing Unit Testing using Jasmine and Karma within an Ionic 3 environment

I am relatively new to Unit Testing and have recently started writing tests for my Ionic 3 Application using Karma and Jasmine. I referred to blogs to configure everything correctly and successfully tested the initialization of App component. Additionally, ...

Could one potentially assign number literals to the keys of a tuple as a union?

Imagine having a tuple in TypeScript like this: type MyTuple = [string, number]; Now, the goal is to find the union of all numeric keys for this tuple, such as 0 | 1. This can be achieved using the following code snippet: type MyKeys = Exclude<keyof ...

Is it feasible to verify the accuracy of the return type of a generic function in Typescript?

Is there a way to validate the result of JSON.parse for different possible types? In the APIs I'm working on, various Json fields from the database need to have specific structures. I want to check if a certain JsonValue returned from the database is ...

Grab a parameter from the URL and insert it into an element before smoothly scrolling down to that

On a button, I have a URL that looks like this: www.mywebsite.com/infopage?scrollTo=section-header&#tab3 After clicking the button, it takes me to the URL above and opens up the tab labeled tab3, just as expected. However, I would like it to direct m ...

`Angular 10 project fails to include JWT refresh token in cross-origin requests`

Our development setup includes an Angular front end and a web service running on a different port on the same machine. The web service is configured to allow access from localhost and the port hosting the Angular application. We are utilizing JWT authenti ...

Activating `routerLinkActive` for multiple components

When working with Angular 2+, I have a navbar set up within an 'Articles' feature module like this: <li> <a routerLinkActive="active" routerLink="current">Current</a> </li> <li> <a router ...

I encountered difficulty in testing the Angular Material Select Component due to complications with the CDK Test Harness

While working on testing a component that utilizes Angular Material Components, I came across the CDK Test Harness and decided to use it to retrieve the count of options in the Mat Select component. You can find more information about the CDK Test Harness ...

Switch from Gulp-TSLint to Gulp-ESLint for enhanced code analysis!

I am currently in the process of updating a Gulp task that uses gulp-tslint to now use gulp-eslint. The code snippet below outlines the changes I need to make: const { src } = require('gulp'); const config = require('./config'); const ...

Encountering "Undefined error" while using @ViewChildren in Angular Typescript

In my application, I am facing an issue with a mat-table that displays data related to Groups. The table fetches more than 50 rows of group information from a data source, but initially only loads the first 14 rows until the user starts scrolling down. Alo ...

Testing Angular - The Art of Mocking InjectionToken

I've been experimenting with testing an Angular service that manages SignalR connections, using the SignalR code as an InjectionToken. Check out the provider file below: // signalr-provider.ts import { InjectionToken } from '@angular/core&apos ...

Differences between Angular's form builder and form control and form groupIn the

What are the benefits of using form control and form group instead of form builder? Upon visiting this link, I discovered: The FormBuilder simplifies creating instances of a FormControl, FormGroup, or FormArray by providing shorthand notation. It helps ...

Choose the initial selection from a list of changing values using Ionic

I'm having trouble selecting the first option in an Ionic select. I've written a condition based on indexes where if the index is 0, checked should be true, but it's still not working. Here is my code: <ion-item> <ion-l ...