我正在尝试创建一个递归函数,该函数将通过类似于带有子目录的目录的对象,并在数组中输出“文件”对象。但是,似乎我得到的是一个数组数组,而不是一个包含我期望看到的对象的简单数组...
代码的底部有一些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'));
最佳答案
您可以传播findEntry
的结果,而不是简单地推送数组。
关于javascript - 如何修复我的递归函数?我正在接收数据数组中的一个,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57030710/