【问题标题】:Recursion maintaining ancestors/parents nested object in JavaScript递归维护 JavaScript 中的祖先/父级嵌套对象
【发布时间】:2014-09-09 18:08:34
【问题描述】:

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

数据结构

[
{
    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;
        }
    }
}

问题

    1234563 /em> 住在 Baby/Safety/Gates
  1. 如果我不返回递归函数,它只能返回根级节点

如果有任何建议或建议,我们将不胜感激。

【问题讨论】:

  • 对我来说听起来像是深度优先搜索。
  • 写一个 ES6 生成器。
  • categories.filter(function(a){return JSON.stringify(a).match('"CategoryName":"Baby"')});根据需要调整其他猫的名字
  • @dandavis 我相信这个问题的一个问题是类别名称“Baby”实际上可以存在多个地方......这就是为什么我有参考类别对象并且需要知道从哪个实例来了
  • 你需要更清楚地说明你想从比赛中走多远。

标签: javascript recursion


【解决方案1】:

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

基本上我使用闭包来保持范围递归并维护它所经历的每次迭代

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 对象和维护父祖先的方法。

【讨论】:

  • 我希望它不会出现混合,因为这很复杂,但它确实有效。感谢您发布答案。
猜你喜欢
  • 2011-11-14
  • 1970-01-01
  • 2012-02-12
  • 2020-11-29
  • 2018-06-07
  • 1970-01-01
  • 2020-10-06
  • 2020-01-26
  • 2021-08-10
相关资源
最近更新 更多