如何提取嵌套对象数组中所有type为file的path属性值组成目标数组
问题原因
你当前的代码仅遍历了数组的第一层元素,而所有type: "file"的对象都嵌套在第一层目录元素的children属性中,没有被遍历到,因此无法筛选出目标数据。
实现方案
你可以通过递归遍历整个树形结构来收集所有文件的路径,参考代码如下:
基础递归写法
function collectFilePaths(arr) { const result = []; for (const item of arr) { if (item.type === "file") { result.push(item.path); } // 存在子级时递归遍历并合并结果 if (Array.isArray(item.children) && item.children.length > 0) { result.push(...collectFilePaths(item.children)); } } return result; } const resultedData = collectFilePaths(data);
简洁版flatMap写法
const collectFilePaths = arr => arr.flatMap(item => item.type === "file" ? [item.path] : Array.isArray(item.children) ? collectFilePaths(item.children) : [] ); const resultedData = collectFilePaths(data);
两种写法最终输出的resultedData都和你期望的结果一致。
内容的提问来源于stack exchange,提问作者Ian
相关产品推荐
相关产品推荐

