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

如何从嵌套有序列表中提取<li>的多维ID数组?

提取嵌套列表中li的data-id为多维数组

问题场景

我有一个嵌套有序列表,结构如下:

<ol id="draggable" class="nested-sort">
    <li data-id="1">Lion</li>
    <li data-id="2">Snake</li>
    <li data-id="3">Butterfly
        <ol data-id="3">
            <li data-id="31">Fish</li>
            <li data-id="32">Cat</li>
            <li data-id="33">Monkey</li>
        </ol>
    </li>
    <li data-id="4">Parrot</li>
</ol>

想要将所有<li>元素的data-id提取为多维数组,尝试了以下jQuery代码:

$( "#draggable li" ).each(function( index ) {
    console.log( index + ": " + $( this ).text() );
});

但输出不符合预期,所有层级的li被平铺输出:

0: Lion
1: Snake
2: Butterfly                                                
  Fish
  Cat
  Monkey
3: Fish
4: Cat
5: Monkey
6: Parrot

解决方案

问题原因

$("#draggable li")是后代选择器,会匹配#draggable下所有层级的<li>元素,包括嵌套在子<ol>里的项,导致无法区分层级,输出平铺的结果。

实现思路

要生成多维数组,需要按层级遍历:

  1. 先遍历顶级<li>(仅#draggable的直接子元素)
  2. 对每个顶级li,检查是否包含子<ol>
  3. 若有子<ol>,递归遍历子列表中的<li>,收集子级id作为当前项的子数组

代码实现

如果需要纯ID的多维数组,可使用以下递归函数:

function getNestedIds($parent) {
  const ids = [];
  $parent.children('li').each(function() {
    const currentId = $(this).data('id');
    const $childOl = $(this).children('ol');
    // 存在子列表则递归收集子ID,否则直接添加当前ID
    if ($childOl.length) {
      ids.push([currentId, getNestedIds($childOl)]);
    } else {
      ids.push(currentId);
    }
  });
  return ids;
}

// 调用函数获取结果
const nestedIds = getNestedIds($('#draggable'));
console.log(nestedIds);

输出结果:

[1, 2, [3, [31, 32, 33]], 4]

如果需要包含层级结构的对象数组(方便后续扩展),可修改为:

function getNestedIds($parent) {
  const ids = [];
  $parent.children('li').each(function() {
    const item = { id: $(this).data('id') };
    const $childOl = $(this).children('ol');
    if ($childOl.length) {
      item.children = getNestedIds($childOl);
    }
    ids.push(item);
  });
  return ids;
}

const nestedIds = getNestedIds($('#draggable'));
console.log(nestedIds);

输出结果:

[
  { id: 1 },
  { id: 2 },
  { id: 3, children: [ { id: 31 }, { id: 32 }, { id: 33 } ] },
  { id: 4 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:01:54