一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

如何按标题分组提取数组中的对应内容对象

时间:2026-07-26 16:49:00 编辑:袖梨 来源:一聚教程网

本文介绍如何将混合字符串与对象的扁平数组,按字符串标题进行逻辑分组,并准确提取每个标题后跟随的所有对象,避免索引计算错误,提供两种实用结构化方案。

本文介绍如何将混合字符串与对象的扁平数组,按字符串标题进行逻辑分组,并准确提取每个标题后跟随的所有对象,避免索引计算错误,提供两种实用结构化方案。

在虚拟列表(virtualization)等场景中,常采用“标题 + 内容块”的扁平数组结构来兼顾渲染性能与语义清晰性。例如数组中交替出现字符串(作为分组标题)和对象(作为该标题下的数据项)。但直接使用 findIndex 配合 slice 容易因相对索引偏移、边界处理不当(如未考虑末尾无后续标题的情况)导致中间分组为空——正如原代码中 nextTitleIndex + 1 在 slice 中被错误地用于非相对起始位置,造成越界或空切片。

更稳健的做法是一次遍历、状态驱动:维护当前标题标识,动态累积内容,而非依赖反复搜索和复杂索引计算。以下是两种生产就绪的实现方式:

✅ 方案一:嵌套数组结构(标题 + 后续所有元素)

const result = [];test.forEach(item => {  if (typeof item === 'string') {    result.push([item]); // 新标题 → 新子数组,首项为标题本身  } else {    // 确保至少有一个分组存在(防止非法输入)    if (result.length > 0) {      result[result.length - 1].push(item);    }  }});// 输出示例:// [//   ["string 1", {prop1: "string 1 obj first"}, ..., {prop1: "string 1 obj last"}],//   ["string 2", {prop1: "string 2 obj first"}, ..., {prop1: "string 2 obj last"}],//   ...// ]

✅ 方案二:键值映射结构(标题为 key,对象数组为 value)

const result = {};let currentTitle = null;test.forEach(item => {  if (typeof item === 'string') {    currentTitle = item;    result[currentTitle] = []; // 初始化空数组,确保 key 存在  } else if (currentTitle !== null) {    result[currentTitle].push(item);  }});// 输出示例:// {//   "string 1": [{prop1: "string 1 obj first"}, ..., {prop1: "string 1 obj last"}],//   "string 2": [{prop1: "string 2 obj first"}, ..., {prop1: "string 2 obj last"}],//   ...// }

⚠️ 注意事项

  • 输入校验建议:若数据可能不规范(如开头非字符串、连续字符串无内容),可在循环中加入 if (!currentTitle && typeof item !== 'string') continue 等防御逻辑;
  • 性能优势:两种方案均为 O(n) 时间复杂度,远优于原 reduce 中每次 findIndex 导致的 O(n²) 操作;
  • 扩展性:方案二更利于后续按标题快速查找(result["string 2"]),而方案一保留原始顺序且天然支持 map 渲染;
  • TypeScript 提示:可定义类型如 Record<string, Array<Record<string, unknown>>> 增强类型安全。

无论选择哪种结构,核心思想一致:用状态代替索引计算,用累积代替切片推导——简洁、可靠、易于维护。

热门栏目