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

如何将任意嵌套深度的UL列表转换为JavaScript/jQuery数组

Convert Nested UL List to Nested JavaScript/jQuery Array (Any Depth)

Problem Overview

You’ve got a deeply nested <ul> structure, but your current jQuery code only handles the first level of nesting. We need a recursive solution to generate a nested array that matches the list’s structure—regardless of how long or deeply nested it is.

Example UL Structure

<div id="main"> 
  <ul> 
    <li> 
      <span>HOME</span> 
      <ul> 
        <li><span>Page 1</span></li> 
        <li><span>Page 2</span></li> 
        <li> 
          <span>Page 3</span> 
          <ul> 
            <li><span>Page a</span></li> 
            <li><span>Page b</span></li> 
            <li><span>Page c</span></li> 
            <li> 
              <span>Page X</span> 
              <ul> 
                <li><span>Page d</span></li> 
                <li><span>Page e</span></li> 
                <li><span>Page f</span></li> 
                <li><span>Page g</span></li> 
              </ul> 
            </li> 
          </ul> 
        </li> 
        <li><span>Page 4</span></li> 
      </ul> 
    </li> 
  </ul> 
</div>

Solution: Recursive Function

The trick here is to use a recursive function that can process any <li> element, including its nested children. Here’s the complete, working code:

// Recursive function to handle a single list item and its children
function processListItem($li) {
  // Grab the text from the direct child span (trim to clean up whitespace)
  const itemText = $li.find(">span:first").text().trim();
  
  // Create the base item object
  const item = {
    brand: itemText,
    children: []
  };
  
  // Check if this list item has a direct child unordered list
  const $childUl = $li.find(">ul");
  if ($childUl.length) {
    // Recursively process each child list item and add to children array
    $childUl.find(">li").each(function() {
      item.children.push(processListItem($(this)));
    });
  }
  
  return item;
}

// Initialize the main array to hold our nested structure
const arr = [];

// Start processing from the top-level list items
$("#main > ul > li").each(function() {
  arr.push(processListItem($(this)));
});

// Log the final nested array
console.log(arr);

How It Works

  • Recursive Logic: The processListItem function takes a jQuery-wrapped <li> element. It first extracts the text from the immediate child <span>, then checks if the <li> has a direct child <ul>.
  • Deep Nesting Handling: If a child <ul> exists, the function loops through each of its <li> elements and calls itself on each one—this is the recursion that handles any depth of nesting.
  • Top-Level Setup: We kick things off by looping through the top-level <li> elements under #main > ul, passing each to our recursive function and adding the result to the main array.

Sample Output

The resulting array will perfectly mirror your nested list structure:

[
  {
    "brand": "HOME",
    "children": [
      {"brand": "Page 1", "children": []},
      {"brand": "Page 2", "children": []},
      {
        "brand": "Page 3",
        "children": [
          {"brand": "Page a", "children": []},
          {"brand": "Page b", "children": []},
          {"brand": "Page c", "children": []},
          {
            "brand": "Page X",
            "children": [
              {"brand": "Page d", "children": []},
              {"brand": "Page e", "children": []},
              {"brand": "Page f", "children": []},
              {"brand": "Page g", "children": []}
            ]
          }
        ]
      },
      {"brand": "Page 4", "children": []}
    ]
  }
]

Key Notes

  • Direct Child Selectors: We use > in selectors (like >span:first, >ul) to ensure we only target immediate children—this prevents accidentally grabbing elements from deeper nested levels.
  • Whitespace Cleanup: The .trim() method removes any extra spaces around the span text, keeping your array data clean.
  • Flexibility: This solution works for any depth of nesting—add more levels to your <ul> and the recursion will handle it automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:07:45