Вы можете взять Array#flatMap
и добавить вложенные найденные элементы, не используя другой параметр для result
.
const
files = { name: "files", is_dir: 1, url: "test", files: [{ name: "folder1", is_dir: 1, url: "test\\/folder1", files: [{ name: "folder1_1", is_dir: 1, url: "test\\/folder1\\/folder1_1", files: [{ name: "index.txt", is_dir: 0, url: "test\\/folder1\\/folder1_1\\/index.txt" }] }, { name: "folder1_2", is_dir: 1, url: "test\\/folder1\\/folder1_2", files: [{ name: "index.txt", is_dir: 0, url: "test\\/folder1\\/folder1_2\\/index.txt" }] }, { name: "index.txt", is_dir: 0, url: "test\\/folder1\\/index.txt" }] }, { name: "folder2", is_dir: 1, url: "test\\/folder2", files: [{ name: "folder2_1", is_dir: 1, url: "test\\/folder2\\/folder2_1", files: [{ name: "index.txt", is_dir: 0, url: "test\\/folder2\\/folder2_1\\/index.txt" }] }, { name: "folder2_2", is_dir: 1, url: "test\\/folder2\\/folder2_2", files: [{ name: "index.txt", is_dir: 0, url: "test\\/folder2\\/folder2_2\\/index.txt" }] }] }, { name: "folder3", is_dir: 1, url: "test\\/folder3", files: [] }, { name: "index.txt", is_dir: 0, url: "test\\/index.txt" }] },
search = (key, val, arr) => arr.flatMap(folderItem => [
...(folderItem[key] === val ? [folderItem] : []),
...search(key, val, folderItem.files || [])
]),
result = search('name', 'folder2', [files]);
console.log(result);