Nesting array based on level

后端 未结 1 651
天涯浪人
天涯浪人 2021-01-29 13:23
0: {content: \"Heading 1 2 3 4 5\", level: 2, anchor: \"heading-1-2-3-4-5\", className: \"testtest\", fontWeight: \"\", …}
1: {content: \"Heading 2\", level: 2, anchor:          


        
1条回答
  •  时光说笑
    2021-01-29 13:29

    You could take a helper array for the levels and one for the indices of each level as adjustment for not zero based or missing levels.

    Imagine, all of your level properties are running from zero and are build upon this value and have no holes, you could take only the line

    levels[index].push({ ...o, children: levels[index + 1] = [] });
    //     ^^^^^                                                      parent
    //                                          ^^^^^^^^^             children
    

    with o.level instead of index.

    Then only levels is uesd to move a node to the right position of the tree. Each level depends on the (smaller) level before.

    The main problem with levels not starting with zero and by having missing levels is to adjust the level to a meaningful index. This is archived by using the level as value and using the index of an array of these values. The rule of getting an index is, if not found, take the last lenght of the array and push the level to the indices array. Otherwise short the indices array to length of index plus one, to prevent deeper nested symbols to be found in the array.

    var data = [{ content: "Heading 1 2 3 4 5", level: 2 }, { content: "Heading 2", level: 2 }, { content: "Inner Heading", level: 2 }, { content: "Heading Level 3", level: 3 }, { content: "Heading Level 3-2", level: 3 }, { content: "Heading Level 4", level: 4 }, { content: "Heading Level 2", level: 2 }, { content: "Heading 4", level: 6 },  { content: "Heading 1", level: 1 }, { content: "Heading 5", level: 5 }],
        result = [],
        indices = [],
        levels = [result];
       
    data.forEach(o => {
        var index = indices.findIndex(level => level >= o.level);
        if (index === -1) {
            index = indices.push(o.level) - 1;
        } else {
            indices.length = index + 1;
        }
        levels[index].push(Object.assign({}, o, { children: levels[index + 1] = [] }));
    });
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
提交回复
热议问题