javascript 递归查找数组中的元素

0s0u357o  于 2023-02-15  发布在  Java
关注(0)|答案(2)|浏览(207)

我有一个对象数组。数组中的每个对象都有一个id和一个item属性,item属性是一个包含其他对象的数组。我需要能够通过id找到数组中的一个元素。下面是我到目前为止所做的一个示例,但是递归函数总是返回undefined。
当我递归调用函数几次时,我如何退出函数并返回项目?

$(function () {
    var treeDataSource = [{
        id: 1,
        Name: "Test1",
        items: [{
            id: 2,
            Name: "Test2",
            items: [{
                id: 3,
                Name: "Test3"
            }]
        }]
    }];
    var getSubMenuItem = function (subMenuItems, id) {
        if (subMenuItems && subMenuItems.length > 0) {
            for (var i = 0; i < subMenuItems.length; i++) {
                var item;
                if (subMenuItems[i].Id == id) {
                    item = subMenuItems[i];
                    return item;
                };
                getSubMenuItem(subMenuItems[i].items, id);
            };
        };
    };
    var searchedItem = getSubMenuItem(treeDataSource, 3);
    alert(searchedItem.id);
});

jsFiddle

2vuwiymt

2vuwiymt1#

您应该替换

getSubMenuItem(subMenuItems[i].items, id);

var found = getSubMenuItem(subMenuItems[i].items, id);
  if (found) return found;

以便在找到元素时返回该元素。
并且要小心属性的名称,javascript区分大小写,因此您还必须替换

if (subMenuItems[i].Id == id) {

if (subMenuItems[i].id == id) {

Demonstration
最终(清洁)代码:

var getSubMenuItem = function (subMenuItems, id) {
    if (subMenuItems) {
        for (var i = 0; i < subMenuItems.length; i++) {
            if (subMenuItems[i].id == id) {
                return subMenuItems[i];
            }
            var found = getSubMenuItem(subMenuItems[i].items, id);
            if (found) return found;
        }
    }
};
bksxznpy

bksxznpy2#

我知道现在已经晚了,但这里有一个更通用的方法

Array.prototype.findRecursive = function(predicate, childrenPropertyName){
    if(!childrenPropertyName){
        throw "findRecursive requires parameter `childrenPropertyName`";
    }
    let array = [];
    array = this;
    let initialFind =  array.find(predicate);
    let elementsWithChildren  = array.filter(x=>x[childrenPropertyName]);
    if(initialFind){
        return initialFind;
    }else if(elementsWithChildren.length){
        let childElements = [];
        elementsWithChildren.forEach(x=>{
            childElements.push(...x[childrenPropertyName]);
        });
        return childElements.findRecursive(predicate, childrenPropertyName);
    }else{
        return undefined;
    }
}

要使用它:

var array = [<lets say an array of students who has their own students>];
var joe = array.findRecursive(x=>x.Name=="Joe", "students");

如果你想过滤而不是查找

Array.prototype.filterRecursive = function(predicate, childProperty){
    let filterResults = [];
    let filterAndPushResults = (arrayToFilter)=>{
        let elementsWithChildren  = arrayToFilter.filter(x=>x[childProperty]);
        let filtered = arrayToFilter.filter(predicate);
        filterResults.push(...filtered);
        if(elementsWithChildren.length){
            let childElements = [];
            elementsWithChildren.forEach(x=>{
                childElements.push(...x[childProperty]);
            });
            filterAndPushResults(childElements);
        }
    };
    filterAndPushResults(this);
    return filterResults;
}

相关问题