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

多维数组操作:将多级分类树数组转换为二级数组的需求

Convert WordPress-Style Category Tree to Level-Based 2D Array

Hey there! Let's work through this problem together. I’ve dealt with WordPress-style menu structures quite a bit, so I get exactly what you’re trying to build—converting that nested category tree into a level-based 2D array where the first index holds all top-level parent IDs, and subsequent indexes hold their respective child levels.

Step 1: Define the Input Structure

First, let’s assume your category array looks something like this (each item has an id, parentId to track its parent, and optionally hasChildren to indicate nested items):

const categoryTree = [
  { id: 1, parentId: 0, hasChildren: true },
  { id: 2, parentId: 1, hasChildren: true },
  { id: 3, parentId: 2, hasChildren: false },
  { id: 4, parentId: 0, hasChildren: false },
  { id: 9, parentId: 0, hasChildren: true },
  { id: 10, parentId: 9, hasChildren: false },
];

Note: Top-level categories typically have a parentId of 0, null, or undefined—adjust the code below if your setup uses a different marker.

Step 2: The Solution Code

Here’s a straightforward function to convert your tree into the desired 2D array:

function convertToLeveledArray(categories) {
  // First, group categories by their parent ID for quick lookup
  const parentToChildrenMap = {};
  categories.forEach(category => {
    const parentKey = category.parentId ?? 'top'; // Use 'top' if parentId is null/undefined
    if (!parentToChildrenMap[parentKey]) {
      parentToChildrenMap[parentKey] = [];
    }
    parentToChildrenMap[parentKey].push(category.id);
  });

  const leveledArray = [];
  // Initialize with top-level categories (parentId: 0 in this case)
  let currentLevelIds = parentToChildrenMap[0] || [];
  leveledArray.push(currentLevelIds);

  // Iterate to build subsequent levels
  while (true) {
    const nextLevelIds = [];
    currentLevelIds.forEach(id => {
      // Add all children of the current level's IDs
      if (parentToChildrenMap[id]) {
        nextLevelIds.push(...parentToChildrenMap[id]);
      }
    });
    // Stop if there are no more child levels
    if (nextLevelIds.length === 0) break;
    leveledArray.push(nextLevelIds);
    currentLevelIds = nextLevelIds;
  }

  return leveledArray;
}

Step 3: Test the Function

Let’s run it with our sample input:

const result = convertToLeveledArray(categoryTree);
console.log(result);

Output:

[
  [1, 4, 9],    // Level 0: Top-level parent IDs
  [2, 10],      // Level 1: Direct children of level 0
  [3]           // Level 2: Children of level 1 items
]

Key Explanations

  • Parent Mapping: We first create a map where each key is a parent ID, and the value is an array of child IDs. This makes it super fast to look up all children for any given parent.
  • Level Building: We start with the top-level IDs, then repeatedly collect all children of the current level to form the next level. We stop when there are no more children left to add.
  • Flexibility: If your top-level categories use null instead of 0, just change parentToChildrenMap[0] to parentToChildrenMap['top'] (or whatever key you used in the mapping step).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:28:46