如何修复我的递归函数?我正在接收数据数组中的一个

时间:2019-07-14 19:59:55

标签: javascript arrays recursion

我正在尝试创建一个递归函数,该函数将通过类似于带有子目录的目录的对象,并在数组中输出“文件”对象。但是,似乎我得到的是一个数组数组,而不是一个包含我希望看到的对象的简单数组...

代码底部有一些console.logs返回:

console.log(findEntry(repAll, '/first')); // ===> [ { name: '/first' }, [] ]
console.log(findEntry(repAll, '/second')); // ===> [ [ { name: '/second' }, { name: '/second' } ] ]

const repAll = { 
    file1: { 
        name: "/first"
    },
    SubDir: { 
        file2: { 
            name: "/second"
        },
        file3: {
            name: "/second"
        }
    } 
};
const req = {};

function findEntry(data, name) {
  let x = [];
    for (const value of Object.values(data)) {
        // Is this a leaf node or a container?
        if (value.name) {
            // Leaf, return it if it's a match
            if (value.name === name) {
                x.push(value);
            }
        } else {
            // Container, look inside it recursively
            const entry = findEntry(value, name);
            x.push(entry);
        }
    }
    return x;
}

console.log('search: /first');
console.log(findEntry(repAll, '/first'));

console.log('search: /second');
console.log(findEntry(repAll, '/second'));

2 个答案:

答案 0 :(得分:2)

您可以传播findEntry的结果,而不是简单地推送数组。

const repAll = { 
    file1: { 
        name: "/first"
    },
    SubDir: { 
        file2: { 
            name: "/second"
        },
        file3: {
            name: "/second"
        }
    } 
};
const req = {};

function findEntry(data, name) {
    let x = [];
    for (const value of Object.values(data)) {
        // Is this a leaf node or a container?
        if (value.name) {
            // Leaf, return it if it's a match
            if (value.name === name) {
                x.push(value);
            }
        } else {
            // Container, look inside it recursively
            x.push(...findEntry(value, name));
        }
    }
    return x;
}

console.log('search: /first');
console.log(findEntry(repAll, '/first'));

console.log('search: /second');
console.log(findEntry(repAll, '/second'));

答案 1 :(得分:0)

采用您的方法:

function findEntry(data, name,x) {

    for (const value of Object.values(data)) {
        // Is this a leaf node or a container?
        if (value.name) {
            // Leaf, return it if it's a match
            if (value.name === name) {
                x.push(value);
            }
        } else {
            // Container, look inside it recursively
            const entry = findEntry(value, name,x);
            x.push(entry);
        }
    }
    return x;
}

现在这样称呼:

let arr=[];
console.log(findEntry(repAll, '/first',arr));