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

如何将连续列表项按顺序合并为list对象并维持原序列?

实现连续列表项的合并逻辑

这是个很典型的结构化内容规整需求,核心就是把连续的列表项批量打包成指定的list对象,同时严格保留原始内容的顺序。我用JavaScript写个实现示例,你可以轻松把逻辑适配到Python、Java等其他语言——核心思路是通用的。

核心实现思路

  1. 双容器跟踪:用一个数组存最终结果,另一个临时数组跟踪当前连续的列表项
  2. 遍历判断:逐个处理原数组的元素:
    • 如果是列表项(ordered-list-item/unordered-list-item),就丢进临时数组
    • 如果是非列表项,先检查临时数组有没有内容——有的话先把它包装成list对象塞进结果,再把当前非列表项加进去
  3. 收尾检查:遍历结束后别忘了处理临时数组里剩下的列表项

代码示例

function mergeContinuousLists(originalContent) {
  const finalResult = [];
  let currentBatch = [];

  originalContent.forEach(item => {
    const isListItem = ['ordered-list-item', 'unordered-list-item'].includes(item.type);
    
    if (isListItem) {
      currentBatch.push(item);
    } else {
      // 先处理之前攒下的列表项
      if (currentBatch.length > 0) {
        finalResult.push({ type: 'list', items: [...currentBatch] });
        currentBatch = [];
      }
      // 加入当前非列表元素
      finalResult.push(item);
    }
  });

  // 处理遍历结束后剩余的列表项
  if (currentBatch.length > 0) {
    finalResult.push({ type: 'list', items: [...currentBatch] });
  }

  return finalResult;
}

// 测试你的输入数据
const inputData = [
  { "type": "heading-1", "text": "A title" },
  { "type": "ordered-list-item", "text": "Ordered Item A" },
  { "type": "unordered-list-item", "text": "Ordered Item B" },
  { "type": "heading-2", "text": "A title" },
  { "type": "ordered-list-item", "text": "Ordered Item A" },
  { "type": "unordered-list-item", "text": "Ordered Item B" }
];

const outputData = mergeContinuousLists(inputData);
console.log(JSON.stringify(outputData, null, 2));

运行结果

执行后会得到你期望的结构化输出:

[
  {
    "type": "heading-1",
    "text": "A title"
  },
  {
    "type": "list",
    "items": [
      {
        "type": "ordered-list-item",
        "text": "Ordered Item A"
      },
      {
        "type": "unordered-list-item",
        "text": "Ordered Item B"
      }
    ]
  },
  {
    "type": "heading-2",
    "text": "A title"
  },
  {
    "type": "list",
    "items": [
      {
        "type": "ordered-list-item",
        "text": "Ordered Item A"
      },
      {
        "type": "unordered-list-item",
        "text": "Ordered Item B"
      }
    ]
  }
]

这个逻辑完全满足你的要求:既保留了所有元素的原始顺序,又把连续的列表项合并到了同一个list对象中,非列表元素保持独立。

内容的提问来源于stack exchange,提问作者stack s

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:32:53