Remove all nested object entries

In my coding project, I have a class structure defined as follows:

class Foo{

    id:string;

    name:string;        

    childFooIds: string[];
}

Within this structure, each instance of Foo can reference its child Foo objects by ID. These Foo instances are stored in an object like so:

fooCollection:{
    [id:string] : Foo
}

Now, I am faced with the challenge of creating a method that can effectively delete a Foo from the fooCollection. Not only do I need to remove the specified Foo instance, but I also need to recursively navigate through its child Foos and their subsequent children to ensure they are removed from the collection as well. Can anyone offer insights or suggestions on how I might approach this task?

Answer №1

If my assumption is correct, the fooCollection variable will be structured as follows:

var fooCollection = {
 '1': new Foo('1','abc1',['3','4']),
 '2': new Foo('2','abc2',['6','7']),
 '3': new Foo('3','abc3',[]),
 '4': new Foo('4','abc4',['8']),
 '5': new Foo('5','abc5',[]),
 '6': new Foo('6','abc6',[]),
 '7': new Foo('7','abc7',[]),
 '8': new Foo('8','abc8',[]),
}

This code snippet shows a method that removes a specific fooId from the fooCollection in a recursive manner.

function removeFoo(fooId){
  var fooObj = fooCollection[fooId];
  if(fooObj){
    for(var i = 0; i < fooObj.childFooIds.length;i++){
        removeFoo(fooObj.childFooIds[i]);
    }
    delete fooCollection[fooId];
  }
}

To execute this function, simply call it like this:

removeFoo('1');

After running the function, the updated fooCollection should resemble the following structure:

{
 '2': new Foo('2','abc2',['6','7']),
 '5': new Foo('5','abc5',[]),
 '6': new Foo('6','abc6',[]),
 '7': new Foo('7','abc7',[])
}

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

Substitute all instances of null bytes

I need to remove null bytes from a string. However, after replacing the null bytes \u0000 in the string let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"} let test = JSON.parse(data).tet.replace("\u0000", ""); I always ...

JavaScript code that only runs during the initial iteration of a loop

I am facing an issue while trying to develop a stopwatch for multiple users using PHP and JavaScript, with MySQL database for user data storage. The problem is that the stopwatch starts when I click on one user but does not work for others. I have attempte ...

Create a React MUI component that allows menu items to become sticky when selected

Is there a way to make the mui MenuItem stay sticky to Select while scrolling down? To see the issue in action, check out this codesandbox example https://codesandbox.io/s/quirky-knuth-5hr2dg?file=/Demo.tsx Simply click on the select and start scrolling ...

Is it possible to achieve a 300 dpi resolution when printing an HTML page?

I've encountered an issue with my web page. It is encoded in HTML and CSS and designed to be the size of an A4 page (300dpi) at 2480 x 3508 pixels. However, when I try to print the page, it is printing in a resolution of 72/96 dpi and splitting into ...

Changing images on hover with jquery

Hello, I've been working on this issue for quite some time now and I could really use some help. I am new to javascript and jquery and currently facing a challenge. I have two images - one black and the other blue. There are 4 black images that should ...

What benefits does storing images in the Next.js public folder offer?

It's interesting how I can place my images practically anywhere and they still work perfectly. But, according to Next.JS, it's actually recommended to store the images in the public folder. What could be the benefits of doing this? ...

Despite a successful request, the React Redux action was not dispatched

I'm currently working on adding authentication to my project. While the user registration part seems to be working, the actions are not being dispatched. Strangely, a similar action for fetching data is working fine and dispatching the actions. Here&a ...

Extracting information from text using machine learning technology

Suppose I am developing a small Chrome extension primarily using JavaScript. Given a list of strings such as: Artist - Song Name Artist, Song Name Song Name - Artist Irrelevant info - Song Name - Artist and so on. I need to extract only the Song Name ...

An error has been encountered in Angular where a source map issue is causing a TypeError due to the

Whenever I work on an Angular project, the browser console usually remains error-free. However, when I opt to include projects > project-name > architect > build > options > "optimization": false in the angular.json file to deactiv ...

What is the process for entering a value into mysql based on the date?

Seeking assistance with a specific coding challenge. The task at hand involves inputting a date, such as '2018-05-08', and based on the user's input, storing the value in different columns of a database table. For instance, if the date is &a ...

Is the variable leaping to a superior scope?

A few days back, I encountered a strange bug in my code that has left me puzzled. It appears that a variable declared within a narrower scope is somehow leaking into a broader one. Any insights into what might be going wrong here? Here's a simplified ...

Properly saving intricate form information in a React application

In my React project, I have a complex form consisting of multiple sub-components. Some parts of the form use nested objects as data, making it a bit challenging to manage. The main component, referred to as EditForm, holds the entire object tree of data. ...

Getting data with a data attribute - a step-by-step guide

I'm attempting to retrieve data from our API using a unique html method involving the data- attribute. I am able to successfully fetch the data directly and load it without any issues. However, when trying to access the data variable from the data att ...

Transferring a string value from C#.NET to JavaScript

So, imagine having a string variable that is passed to a JavaScript function using the following code. Chart1.Series["Series1"].Points[counter].MapAreaAttributes = "onmouseover=\"showAlert("+tempString+",event);\""; The JavaScript function look ...

Is there a way to add the filter method to this code without removing the map method already in place?

I am interested in creating a filter for my array of jokeComponents to only show questions with less than X characters. Is there a way to implement the filter method into this code without removing the map function? import React from "react" import ...

Issue with Canvas.doDataUrl not functioning properly in presence of an image on canvas

It seems like the code I have tried only works for local images. Can someone share a working code snippet for this? Here is what I've attempted: var base_image = new Image(); base_image.src = ("/img.png"); base_image.onload = function(){ var co ...

The $emit method in Vue seems to be ineffective when used on the parent component, yet it functions properly when used on the

I have a component called "register" which contains an event listener @submit.prevent inside the template, and I am using $emit to send the data. When I console.log within the method of the component itself, it works fine. However, when I try to access the ...

Choosing the type attribute of an input tag by using a javascript variable as a condition: What's the best approach?

I am currently utilizing an input tag on the client side to receive text input. <input type="text" class="form-control" placeholder="Enter Message" id="messageText" autofocus/> My goal now is to dynamically set the type attribute based on a Javasc ...

Ways to prevent altering values in ngModel

I am working on a component in Angular 5 where I am trying to write unit tests to ensure that when the component is disabled, it should not be possible to set a value to its model. However, even after disabling it, I am still able to change the value. [ ...

Modified the component based on the state passed from another component

One issue I'm facing is with my hamburger component in TodoHeader.jsx. It only has a color prop, no className prop. I noticed that when using the ternary operator to change its color, it only takes effect after a page reload. On the other hand, FontAw ...