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 Angular modal popup not repositioning upon clicking elsewhere on the page

I have encountered an issue with modal popups on my website. Specifically, I have approximately 100 table elements and when I try to edit the element #100, the modal popup appears at the bottom of the page. However, if I scroll back up and click on eleme ...

Troubleshooting issues with Bootstrap's responsiveness configuration

I've been working on creating a responsive user login page using Angular 5. It looks great on full-screen display. https://i.sstatic.net/YQrL5.png However, when I resize the browser window, the responsiveness seems to break. https://i.sstatic.net/4 ...

When working with Expo and React Native in TypeScript, VS code IntelliSense recommends using 'react-native/types' instead of just 'react-native'

My React Native TypeScript setup is showing react-native/types instead of react-native in IntelliSense. How can I fix this issue? I initialized my project using npx create-expo-app MyApp --template Typescript. Here is my tsconfig.json configuration. { ...

Show dynamic JSON data in a nested format on the user interface with Aurelia's Treeview component

In the visual representation provided, there are currently three objects in the array. These objects, referred to as "parents", each have their own set of "children". The complexity lies in the fact that a parent element can also serve as a child element w ...

Problem encountered with @HostListener

In an Angular component, I have the following code snippet that is functioning as intended: @HostListener('document:click', ['$event']) onClick(event) { if(!this.eRef.nativeElement.contains(event.target)) { console.log("clicked out ...

Issue encountered in loading css and js folders during the build of the Angular2 application due to the files not being found

I have developed an Angular 2 application that utilizes Node.js server APIs. After building the app using nd b, the files were generated in the dist folder. Where should I specify the production URL for the build so that all CSS and JS files load properly? ...

Using the spread operator to modify an array containing objects

I am facing a challenge with updating specific properties of an object within an array. I have an array of objects and I need to update only certain properties of a single object in that array. Here is the code snippet I tried: setRequiredFields(prevRequir ...

What is the best approach for managing errors between Node.js and Angular 2?

I have a simple task at hand. Let's consider a scenario where a user can submit news through a form that has two fields: title and content. The title field is required, which can be validated both on the client side and server side using the following ...

How can the map function be executed sequentially every second, using async functions, fetch API, and promises, without running in parallel?

I am facing an issue with my map function, as it needs to fetch data from an online API that only allows one request per second. I attempted to solve this problem by implementing the following code: const sleep = (ms: number) => { return new Promise(( ...

The PrimeNG pie chart will sporadically appear and adjust its display when the resolution changes

I recently encountered an issue with a primeng pie chart that I am using, which pulls dynamic data from the back-end. Previously, when using static data, the pie chart functioned perfectly. However, after integrating dynamic data, the chart now seems to di ...

Searching for a single cell within an HTML table

I've been on the hunt for a code that can search through a table and show just one cell. I tried creating my own, but finally stumbled upon one that seems to work perfectly, except for one hiccup. When the search bar is cleared, it displays the first ...

Troubleshooting image loading issues when updating the base URL in an Angular JS project

I am trying to update the base URL for my application. Currently, when I load the application, the URL shows up as http://localhost:4200/#/, but I want it to be http://localhost:4200/carrom/ instead. To accomplish this, I modified the base URL and now th ...

Are you familiar with Mozilla's guide on combining strings using a delimiter in Angular2+?

I found myself in need of concatenating multiple string arguments with a specific delimiter, so after searching online, I stumbled upon a helpful guide on Mozilla's website that taught me how to achieve this using the arguments object. function myCo ...

Can Angular 2 Material Tabs be dynamically filled with a For Loop subscription?

Is it possible to populate a dynamic number of tabs on an Angular 2 website using a For Loop that subscribes to data from a database service? My dataset is categorized by Classes A, B, and C, each with Sub-Classes 1 and 2. I want to dynamically create thr ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...

Balancing website speed with capturing product impression

I've been tasked with capturing impressions of all the products visible in the viewport on a website that features thousands of products. To achieve this, I implemented a directory and utilized the IntersectionObserver, which was referenced within the ...

Using RxJS and the combineLatest function can be hit or miss in terms of reliability

When you call this function multiple times with the values of observables obs1 and obs2 being the same each time, the returned array may not always be the same. getUniqueProducts(obs1: Observable<any>, obs2: Observable<any>): Observable<any& ...

The 'Refused to execute inline event handler' error occurs when using Angular

I am encountering a specific error in my Angular application when trying to execute an inline event handler. The error message can be seen below: https://i.stack.imgur.com/jSAIz.png Refused to execute inline event handler because it violates the following ...

Securing Your Next.js Web App with Session Authentication

I have encountered a challenge while integrating NextAuth authentication into my React.js web application. To ensure seamless user authentication across the entire app, I am attempting to wrap a SessionProvider around the root component. However, VSCode ...

Navigating to the end of a list using Angular's scroll feature

I'm trying to figure out how to automatically scroll to the bottom of a list in TypeScript, can someone help me with this? Here's a similar example I found that uses jQuery (I specifically need it in TypeScript): Scroll to bottom of list wit ...