在JavaScript中递归维护祖先/父嵌套对象

在JavaScript中递归维护祖先/父嵌套对象,javascript,recursion,Javascript,Recursion,我有一个非常深的嵌套类别结构,我得到了一个类别对象,它可以存在于任何深度。我需要能够遍历所有类别节点,直到找到请求的类别,并且能够全程捕获其父类别 数据结构 [ { CategoryName: 'Antiques' }, { CategoryName: 'Art', children: [ { CategoryName: 'Digital', children: [ {

我有一个非常深的嵌套类别结构,我得到了一个类别对象,它可以存在于任何深度。我需要能够遍历所有类别节点,直到找到请求的类别,并且能够全程捕获其父类别

数据结构

[
{
    CategoryName: 'Antiques'
},
{
    CategoryName: 'Art',
    children: [
        {
            CategoryName: 'Digital',
            children: [
                {
                    CategoryName: 'Nesting..'
                }
            ]
        },
        {
            CategoryName: 'Print'
        }
    ]
},
{
    CategoryName: 'Baby',
    children: [
        {
            CategoryName: 'Toys'
        },
        {
            CategoryName: 'Safety',
            children: [
                {
                    CategoryName: 'Gates'
                }
            ]
        }
    ]
},
{
    CategoryName: 'Books'
}
]

代码当前已就位

function findCategoryParent (categories, category, result) {
    // Iterate through our categories...initially passes in the root categories
    for (var i = 0; i < categories.length; i++) {

        // Check if our current category is the one we are looking for
        if(categories[i] != category){
            if(!categories[i].children)
                continue;

            // We want to store each ancestor in this result array
            var result = result || [];
            result.push(categories[i]);
            // Since we want to return data, we need to return our recursion
            return findCategoryParent(categories[i].children, category, result);
        }else{
            // In case user clicks a parent category and it doesnt hit above logic
            if(categories[i].CategoryLevel == 1)
                result = [];

            // Woohoo...we found it
            result.push(categories[i]);
            return result;
        }
    }
}
函数findCategoryParent(类别、类别、结果){
//遍历我们的类别…最初传入根类别
对于(变量i=0;i
问题
  • 如果我返回我的递归函数,它对“艺术”及其所有子类都很有效。但由于它返回,Baby类别永远不会被击中,因此也永远找不到生活在Baby/Safety/Gates中的“Gates”

  • 如果我不返回递归函数,它只能返回根级别的节点


  • 如果您有任何建议,我将不胜感激。

    好吧,我相信我找到了一个似乎对我的大脑有效的解决方案,但我不知道为什么我的大脑花了这么长时间才弄明白……但解决方案当然是封闭的

    本质上,我使用闭包来保持一个限定范围的递归,并维护它经过的每个迭代

    var someobj = {
        find: function (category, tree, path, callback) {
            var self = this;
            for (var i = tree.length - 1; i >= 0; i--) {
    
                // Closure will allow us to scope our path variable and only what we have traversed
                // in our initial and subsequent closure functions
                (function(){
                    // copy but not reference
                    var currentPath = path.slice();
    
                    if(tree[i] == category){
                        currentPath.push({name: tree[i].name, id: tree[i].id});
                        var obj = {
                            index: i,
                            category: category,
                            parent: tree,
                            path: currentPath
                        };
                        callback(obj);
                    }else{
                        if(tree[i].children){
                            currentPath.push({name: tree[i].name, id: tree[i].id});
                            self.find(category, tree[i].children, currentPath, callback);
                        }
                    }
    
                })(tree[i]);
            }
        },
    
        /**
         * gets called when user clicks a category to remove
         * @param  {[type]} category [description]
         * @return {[type]}          [description]
         */
        removeCategory: function (category) {
            // starts the quest for our category and its ancestors
            // category is one we want to look for
            // this.list is our root list of categoires,
            // pass in an intial empty array, each closure will add to its own instance
            // callback to finish things off
            this.find(category, this.list, [], function(data){
                console.log(data);
            });
        }
    }
    

    希望这能帮助其他需要遍历javascript对象和维护父祖先的人。

    听起来像是深度优先搜索。编写一个ES6生成器。categories。filter(函数(a){return JSON。stringify(a)。match('CategoryName:'Baby'));根据需要对其他cat发动机进行调整names@dandavis我相信这一个的一个问题是,类别名称“Baby”实际上可以存在多个位置…这就是为什么我有引用类别对象,并且需要知道该实例来自哪个位置。你需要更清楚地说明你想从一场比赛中走多远。我希望它不会出现因为这很复杂,但它能工作。谢谢你发布答案。