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: "heading-2", fontWeight: "", textTransform: "", …}
2: {content: "Inner Heading", level: 2, anchor: "inner-heading", fontWeight: "", textTransform: "", …}
3: {content: "Heading Level 3", level: 3, anchor: "heading-level-3", fontWeight: "", textTransform: "", …}
4: {content: "Heading Level 3-2", level: 3, fontWeight: "", textTransform: "", noBottomSpacing: false, …}
5: {content: "Heading Level 4", level: 4, anchor: "heading-level-4", fontWeight: "", textTransform: "", …}
6: {content: "Heading Level 2", level: 2, anchor: "heading-level-2", fontWeight: "", textTransform: "", …}
7: {content: "Heading 4", level: 6, anchor: "heading-4", fontWeight: "", textTransform: "", …}
我在JavaScript中有这个数组,需要根据级别进行嵌套。
例如,
level 2
level 2
level 2
level 3
level 3
level 4
level 2
level 4
嵌套此内容的最佳方法是什么?
到目前为止,我已经尝试过:
const nestHeading = heading => {
const nestedHeadersLength = nestedHeaders.length;
if ( nestedHeadersLength >= 1 ) {
const previousIndex = nestedHeadersLength - 1;
if ( previousIndex >= 0 ) {
if (
heading.level !== nestedHeaders[ previousIndex ].level &&
heading.level > nestedHeaders[ previousIndex ].level
) {
nestedHeaders[ previousIndex ].innerHeadings.push( heading );
} else {
nestedHeaders.push( heading );
}
}
} else {
nestedHeaders.push( heading );
}
};
标题是原始数据集中的每个项目。
您可以为每个级别采用一个辅助数组,为每个级别的索引采用一个辅助数组,作为对不基于零或缺失级别的调整。
想象一下,您所有的
level
属性都从零开始运行,并且都基于此值并且没有空洞,您只能使用该行levels[index].push({ ...o, children: levels[index + 1] = [] }); // ^^^^^ parent // ^^^^^^^^^ children
用
o.level
代替index
。然后仅将
levels
用于将节点移至树的正确位置。每个级别取决于之前的(较小)级别。级别不是从零开始并且缺少级别的主要问题是将级别调整为有意义的索引。通过使用级别作为符号/抽象值并使用这些符号数组的索引来存档该文件。获取索引的规则是,如果找不到索引,则取数组的最后长度,然后将级别/符号推入
indices
数组。否则,将indices
数组缩短为length
的index
加一,以防止在数组中发现较旧的符号。
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 }],
result = [],
indices = [],
levels = [result];
data.forEach(o => {
var index = indices.indexOf(o.level);
if (index === -1) {
index = indices.push(o.level) - 1;
} else {
indices.length = index + 1;
}
levels[index].push({ ...o, children: levels[index + 1] = [] });
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }