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

如何基于10位ID键对大量数组项实现树形逻辑分组?

Build Hierarchical Tree from 10-Digit IDs Dynamically

Alright, I’ve worked through similar hierarchical grouping problems before, so let’s break this down step by step. Your 10-digit IDs follow a clear pattern—each pair of digits represents a level in the tree (e.g., first 2 digits = level 1, next 2 = level 2, up to 5 total levels). Here’s how to build the tree dynamically without hardcoding any parent-child relationships, even for large datasets:

Step 1: Understand the Parent-Child ID Relationship

For any node, its parent ID is derived by:

  1. Splitting the 10-digit ID into 5 two-digit segments (e.g., 0201010100 becomes ["02", "01", "01", "01", "00"])
  2. Finding the last non-"00" segment (this is the segment that identifies the current node’s branch under its parent)
  3. Replacing that segment with "00" and setting all subsequent segments to "00" to get the parent ID

Example:

  • Node d (ID: 0201010100) → Last non-"00" segment is the 4th ("01") → Parent ID is 0201010000 (node c)
  • Node c (ID: 0201010000) → Last non-"00" segment is the 3rd ("01") → Parent ID is 0201000000 (node b)
  • Root nodes (like a with ID 0200000000) have no non-"00" segments after the first, so they become top-level nodes.

Step 2: Code Implementation (JavaScript)

First, we’ll map all nodes for quick lookup, then link each node to its parent:

// Your raw dataset
const rawData = [
  {"ID":"0200000000", "Name":"a"},
  {"ID":"0201000000", "Name":"b"},
  {"ID":"0201010000", "Name":"c"},
  {"ID":"0201010100", "Name":"d"},
  {"ID":"0201010200", "Name":"e"},
  {"ID":"0201010300", "Name":"f"},
  {"ID":"0300000000", "Name":"g"},
  {"ID":"0301000000", "Name":"h"},
  {"ID":"0301010000", "Name":"i"}
];

// 1. Create a map of nodes with empty children arrays
const nodeMap = {};
rawData.forEach(item => {
  nodeMap[item.ID] = {...item, children: []};
});

// 2. Link each node to its parent
const treeRoots = [];
rawData.forEach(item => {
  const currentNode = nodeMap[item.ID];
  let parentId = null;
  
  // Split ID into 2-digit segments
  const segments = item.ID.match(/.{1,2}/g);
  // Find the last non-"00" segment index
  let lastNonZeroSegIndex = -1;
  for (let i = segments.length - 1; i >= 0; i--) {
    if (segments[i] !== "00") {
      lastNonZeroSegIndex = i;
      break;
    }
  }
  
  // Generate parent ID if current node isn't a root
  if (lastNonZeroSegIndex > 0) {
    const parentSegments = [...segments];
    parentSegments[lastNonZeroSegIndex] = "00";
    // Set all segments after to "00"
    for (let i = lastNonZeroSegIndex + 1; i < parentSegments.length; i++) {
      parentSegments[i] = "00";
    }
    parentId = parentSegments.join('');
  }
  
  // Attach to parent or add as root
  if (parentId && nodeMap[parentId]) {
    nodeMap[parentId].children.push(currentNode);
  } else {
    treeRoots.push(currentNode);
  }
});

// treeRoots now holds your full hierarchical tree!
console.log(treeRoots);

Step 3: Render the Tree with jQuery (Optional)

If you need to display this tree in the DOM, use a recursive function to generate HTML:

// Recursive function to build tree HTML
function generateTreeHTML(nodes) {
  let html = '<ul>';
  nodes.forEach(node => {
    html += `<li>${node.Name}`;
    // Add children if present
    if (node.children.length > 0) {
      html += generateTreeHTML(node.children);
    }
    html += '</li>';
  });
  html += '</ul>';
  return html;
}

// Render to a container element
$('#tree-container').html(generateTreeHTML(treeRoots));

Key Benefits

  • Dynamic: Works for any number of levels or nodes, no hardcoding required
  • Efficient: Runs in O(n) time (each node is processed twice), perfect for large datasets
  • Scalable: Handles new ID patterns as long as they follow the 2-digit per level rule

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:24:23