多维数组操作:将多级分类树数组转换为二级数组的需求
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
nullinstead of0, just changeparentToChildrenMap[0]toparentToChildrenMap['top'](or whatever key you used in the mapping step).
内容的提问来源于stack exchange,提问作者Corcunda

