Javascript 删除nodeJS应用程序中的所有组和子级

Javascript 删除nodeJS应用程序中的所有组和子级,javascript,function,recursion,tree,Javascript,Function,Recursion,Tree,我需要我的小nodeJS应用程序的帮助。我需要创建一个函数来删除树中的嵌套组。 iv'e调试了我的树搜索递归,效果很好。 但是我的删除功能没有删除任何内容。 我需要找到父对象并将其从数组中删除。 树看起来像这样: class Group { constructor(name, parent) { this.name = name; this.parent = parent || null; this.children = [];

我需要我的小nodeJS应用程序的帮助。我需要创建一个函数来删除树中的嵌套组。 iv'e调试了我的树搜索递归,效果很好。 但是我的删除功能没有删除任何内容。 我需要找到父对象并将其从数组中删除。 树看起来像这样:

class Group {
    constructor(name, parent) {
        this.name = name;
        this.parent = parent || null;
        this.children = [];
        this.users = new users || null;
    }
}
class groups {
    constructor() {
        this.root = new Group('root');
    }
}
工作树搜索功能(请随意使用!) 和不起作用的删除功能

findGroupByName(name) {
    if (!name)
        return null;

    return this._findGroupByNameInternal(this.root, name);
}

_findGroupByNameInternal(group, name) {
    if (!group)
        return null;

    if (group.name === name)
        return group;

    for (const g of group.children) {
        const result = this._findGroupByNameInternal(g, name);

        if (!result)
            continue;

        return result;
    }
}
removeByName(name) {
    if (!this.children)
        return;

    const groupToRemove = this.findGroupByName(name);

    if (groupToRemove) {
        this.children = this.children.filter(g => g !== groupToRemove);
    }
}
菜单处理程序

function removeGroup(callback) { //need fixing
    rl.question('Enter group name to delete: \n', (groupName) => {
        let parentGroup = programdata.groups.findGroupByName(groupName);
        programdata.groups.removeByName(groupName)
        console.log(parentGroup);
        callback()
    })
}

function showGroups(callback) {
    callback()
}

这对您不起作用,因为
\u findGroupByNameInternal()
返回的组不一定是您在上调用的
removeByName()
实例的子对象。因此,当您尝试
filter()
实例子对象时,它可能不在那里-它可能是孙子或更深层的子对象。当您找到该组并且仍然知道其父组时,需要将其删除。有很多方法可以做到这一点,但这里有一个简单的方法:

类组{
构造函数(){
this.root=新组(“root”);
}
removeByName(名称){
this.root.removeByName(名称)
}
}
班级{
构造函数(名称、父级){
this.name=名称;
this.parent=parent | | null;
这是:children=[];
}
removeByName(名称){
//这个名字在儿童中是什么?
让index=this.children.findIndex(g=>g.name==name)
如果(索引>-1){
//删除它
此.children.splice(索引,1)
console.log(`removed${name}from${this.name}`)
}否则{
//否则会在孩子身上重现
this.children.forEach(child=>child.removeByName(name))
}
}
}