You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取嵌套对象数组中所有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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 00:06:06