Florentin Le Moal
Florentin Le Moal

Reputation: 187

Parse a list of heading in a document to a sorted tree

I'm trying to parse a list of headings (h1, h2, etc.) to obtain the table of content in a well structured javascript variable (kinda like a tree).

Here's the structure of my document:

<div id="content">
    <h1>The content</h1>blah
    <h2 class="show-in-toc">Test 1</h2>
    <h3 class="show-in-toc">Test 1.1</h3>
    <h3 class="show-in-toc">Test 1.2</h3>
    <h4 class="show-in-toc">Test 1.2.1</h4>
    <h4 class="show-in-toc">Test 1.2.2</h4>
    <h2 class="show-in-toc">Test 2</h2>
    <h3 class="show-in-toc">Test 2.1</h3>
    <h4 class="show-in-toc">Test 2.1.1</h4>
    <h3 class="show-in-toc">Test 2.2</h3>
</div>

And here's what I'm trying to get:

[
    {"text": "Test 1","level": 2, "children": [
        {"text": "Test 1.1","level": 3,"children": []},
        {"text": "Test 1.2", "level": 3, "children": [
            {"text": "Test 1.2.1", "level": 4, "children": []},
            {"text": "Test 1.2.2", "level": 4, "children": []}
        ]}
    ]},
    {"text": "Test 2", "level": 2, "children": [
        {"text": "Test 2.1", "level": 3, "children": [
            {"text": "Test 2.1.1", "level": 4, "children": []}
        ]},
        {"text": "Test 2.2", "level": 3, "children": []}
    ]}
]

I'm guessing the function should be recursive and would look like this:

headings = $('.show-in-toc:header'); // Maybe .toArray() ?
toc = generateToc(headings, 2); // With 2 being the starting level

I tried to inspire an algorithm from this subject but I didn't get any result (they're directly putting the result into a dom element).

Have you any suggestion to guide me? Thank you in advance

Upvotes: 1

Views: 219

Answers (1)

Florentin Le Moal
Florentin Le Moal

Reputation: 187

I finally managed to do the algorithm I wanted, thank to the comments that gave me a bit of a hint. Here's the result on a JSFiddle, I'll explain it and comment it later even though it's pretty simple to understand.

function headerTagToObject(tag, level) {
    tag = $(tag);
    return {
        'title': tag.text(),
        'level': level,
        'children': []
    }
}

function generateToc(level, filter = undefined, initial_parent = undefined, parent = undefined) {
    var result, tags;
    result = [];
    if (parent) {
        tags = $(parent).nextUntil('h' + (level - 1), 'h' + level).filter(filter);
    } else {
        if (initial_parent) {
            tags = $(initial_parent).find('h' + level).filter(filter);
        } else {
            tags = $('h' + level).filter(filter);
        }

    }

    tags.each(function(i, tag) {
        var tagResult;
        tagResult = headerTagToObject(tag, level);
        tagResult['children'] = generateToc(level + 1, filter, initial_parent, tag);
        result.push(tagResult);
    });
    return result;
}

// Usage
result = generateToc(2, '.show-in-toc', '#content');

Upvotes: 1

Related Questions