JavaScript数组内元素分组:按父层级分组数据结构问题
Group Chapters by Parent Level in JavaScript
Got it, let's solve this problem of grouping your flat chapter array into a nested structure based on their level values. Here's a practical, efficient approach that works for any depth of levels:
Step-by-Step Solution
1. Core Logic
We'll use a map to keep track of all nodes as we process them, making it easy to find parent nodes quickly. For each item:
- Split its
levelstring into an array of segments (e.g.,'1.1.1'→['1', '1', '1']) - Generate the parent level by removing the last segment (e.g.,
['1', '1']→'1.1') - Add the current item as a child to its parent node (we'll handle edge cases where a parent might be missing, though your data seems to have valid parent entries)
2. Code Implementation
const arr = [ { level: '1.1', name: 'group title 1' }, { level: '1.1.1', name: 'group section 1.1.1' }, { level: '1.1.2', name: 'group section 1.1.2' }, { level: '1.1.3', name: 'group section 1.1.3' }, { level: '1.2', name: 'group title 2' }, { level: '1.2.1', name: 'group section 1.2.1' }, { level: '1.3', name: 'group title 3' }, { level: '1.3.1', name: 'group section 1.3.1' } ]; function groupChaptersByParent(chapters) { const nodeMap = new Map(); const root = { children: [] }; chapters.forEach(chapter => { // Create a node for the current chapter, initialize an empty children array const node = { ...chapter, children: [] }; nodeMap.set(chapter.level, node); // Split the level into segments to locate the parent const levelSegments = chapter.level.split('.'); if (levelSegments.length > 1) { // Build the parent level string by removing the last segment const parentLevel = levelSegments.slice(0, -1).join('.'); const parentNode = nodeMap.get(parentLevel); // Add current node to its parent's children list if (parentNode) { parentNode.children.push(node); } else { // Fallback: if parent doesn't exist, add to root (adjust this if needed) root.children.push(node); } } else { // Top-level chapters (like '1') get added directly to root root.children.push(node); } }); // Return the top-level groups (1.1, 1.2, etc.) with their nested children return root.children; } // Test the function const groupedChapters = groupChaptersByParent(arr); console.log(JSON.stringify(groupedChapters, null, 2));
3. Output Result
When you run the code, you'll get a clean nested structure where each top-level group contains its child sections:
[ { "level": "1.1", "name": "group title 1", "children": [ { "level": "1.1.1", "name": "group section 1.1.1", "children": [] }, { "level": "1.1.2", "name": "group section 1.1.2", "children": [] }, { "level": "1.1.3", "name": "group section 1.1.3", "children": [] } ] }, { "level": "1.2", "name": "group title 2", "children": [ { "level": "1.2.1", "name": "group section 1.2.1", "children": [] } ] }, { "level": "1.3", "name": "group title 3", "children": [ { "level": "1.3.1", "name": "group section 1.3.1", "children": [] } ] } ]
Key Notes
- This approach handles any depth of levels (e.g.,
1.1.1.1would automatically nest under1.1.1) - The
nodeMapensures we look up parent nodes in O(1) time, making the overall process O(n) (super efficient even for large arrays) - If your data might have missing parent entries, the fallback adds those nodes to the root—you can tweak this logic to fit your specific use case
内容的提问来源于stack exchange,提问作者pro
相关产品推荐
相关产品推荐

