Discovering elements containing a particular value within a deeply nested array of indefinite depth

I am working with an array containing objects that may have unknown and varying nesting depths. Here is an example of such an array:

let exampleArray = [
  {
    id: 'some-id',
    label: "Item 1",
    children: [
      {
        id: 'some-id',
        label: "Child 1",
        children: [
          {
            id: 'some-id', // How to find this for example?
            label: "Child 2",
            children: []
          }
        ]
      }
    ]
  },
  {
    id: 'some-id',
    label: "Item 2",
    children: [
      {
        id: 'some-id',
        label: "Child 1",
        children: [
          {
            id: 'some-id',
            label: "Child 2",
            children: []
          }
        ]
      }
    ]
  }
]

Each item in the array can contain a nested array called children, following a similar structure as the parent object.

The task at hand:

If I need to remove a specific nested element based on its ID, how should I go about it? Iterating through the entire array with a predefined number of loops might not be efficient, given the dynamic nature of nesting levels.

If I have the ID of the child element, can I implement a logic that says: "Iterate through the entire array, including all nested layers, to locate the element with the specified ID xy."

What would be the best approach to manage such complex nested arrays?

Answer №1

If you're in need of a solution, consider utilizing a recursive function:

function removeById(data, id){
    for(var index = 0; index < data.length; index++){
        if(data[index].id === id){
            data.splice(index, 1); // Remove the element from the array if it matches
        }
        else{
            removeById(data[index].children, id);
        }
    }
}

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

The navigation functionality of Angular's router.navigate is failing to operate within the context

In my NewCategoryComponent, I have a form to gather details and a WarningComponent that will appear when the user attempts to close the form. When the user clicks the close (x) icon, they will be presented with a warning message using Mat Dialog (Mat Dial ...

utilize Java version specifically designed for integrating with Angular framework and SOAP web services

One question I've been pondering: we currently have a project built on Java 6 and GWT, but we're considering migrating to Angular (using SOAP web services). Will Java 6 be compatible with Angular for the backend, or will we need to upgrade to Jav ...

Choosing a single radio button value within a nested ng-repeat loop in AngularJS

Help needed with selecting only one radio button value in nested ng-repeat. Please review the source code and suggest any potential mistakes. <form ng-submit="save()"> <div ng-repeat="x in surveyLst"> <div class="row"> < ...

The character replacement function does not seem to be functioning properly in DialogFlow following the use of

Is there a way to replace commas with colons in the 'setTime' result? I attempted to create another variable and then use the replace() method, but it resulted in an error message stating "Webhook call failed. Error: 500 Internal Server Error". ...

What is the reason for needing to refresh when submitting form data in a Node application with an HTTP POST

Code Snippet - Angular .state('studentInfo.newStudent', { url : '/new/student', templateUrl: 'students/new-student.html', controller : function($state, $http){ this.saveStudent = func ...

Is there a secure alternative in Typescript for handling null values, such as a "safe operator"?

I'm currently working on implementing a feature in my Angular application where I need to toggle the visibility of a div using ngIf. Below you can find the snippet of HTML code I am using: <div *ngIf="damageReportToPolice()"> </div> Her ...

Mapping an array based on its individual values

How can I sum values in an array of objects based on a specific condition? [{amount:100, prefix:'a'},{amount:50, prefix:'b'},{amount:70, prefix:'a'},{amount:100, prefix:'b'}] Is there a method to map and calculate t ...

Looking to locate the child div elements within a parent div

I am having trouble determining the individual lengths of child divs within parent classes that share the same name. For example: <div class="main-div"> <div class="parent"> <div class="child"></div> <div class= ...

I am looking to dynamically add and remove an active link on my sidebar using JavaScript

Looking to create a dynamic website with interactive features like adding and removing active links upon clicking, and smooth transitioning between sections using JavaScript. Feel free to skip over the SVG code. HTML source code <div class="s ...

Comparison of Grant and Passport.js: Which One to Choose?

Are you unsure about the distinctions between Grant and Passport.js? How do you decide when to utilize Grant over passport.js, and vice versa? If your goal is to create a social media platform that tracks user activities and posts them on a news feed, whi ...

Adjust the image size to match the height of its parent element and ensure it stays resized when the window is

Looking for some assistance with my code. Here's an example of what I'm working on - http://jsfiddle.net/urK7t/ You can also view the full-size page here - In terms of the concept: I am trying to create a DIV element that has 100% width and h ...

Running code sequentially in a Node.js controller

Recently delved into the world of Node.js, and I'm currently tackling the challenge of running this code synchronously in my controller. Quest.js async function create(req, res, next) { const formValue = req.body['form']; ...

Retrieve a non-existent property from an object using the forEach method

Within my data array, I have a collection of objects with varying properties. Some objects may have all the properties while others might be missing certain ones. const data = [ { car: 12, airplane: 42, peoples: 2, }, ...

Implement Logo Size Reduction on Scroll in Navigation Bar

My design includes a div with a height of 120px, larger than the 75px navbar. When scrolling begins, I want the logo to transition to match the height of the navbar. Despite my efforts to toggle a CSS class, I am unable to achieve the desired effect. What ...

Assume we have two positive integers, N and X. In this scenario, N represents the total number of patients, while X denotes the time duration, measured in minutes, between the arrival

Suppose you are given two positive integers N and X. Here, N represents the total number of patients while X indicates the time duration (in minutes) after which a new patient will arrive. The doctor only provides 10 minutes to each patient for consultatio ...

Issues encountered with asp.net javascript function not executing

Having trouble getting a javascript function to execute via jquery in an asp.net setting. Despite trying various approaches, the function doesn't run upon clicking the button. I've experimented with omitting jquery and using a static html input c ...

Error: Unable to access the 'push' property of an undefined value

42 | <Router> 43 | <ul> > 44 | {this.state.movies.map(movie => <li onClick={() => this.handleMovieClick(movie.title)}>{movie.title}{movie.description} <button type="button" onClick={() => this.deleteMovie(movie.title)}& ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

Angular is having trouble progressing after a stylesheet has been chosen

$ ng new my-app ? Do you want to include Angular routing in your project? Yes ? Which stylesheet format do you prefer to use? CSS Unfortunately, the next steps are not proceeding as expected. The process seems to be stuck and even keyboard shortcuts like ...

Ways to move down only one level of an element's children, excluding sub-levels

When implementing this code snippet: jQuery: $(this).next().slideDown() with a selector :$(this).next() HTML: <li class="sub-menu two-level-collapse"> <a href="javascript:void(0);" class="two-level-collapse parent">< ...