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 );
}
};
标题是原始数据集中的每个项目。
答案 0 :(得分:1)
您可以为每个级别获取一个辅助数组,为每个级别的索引获取一个辅助数组,以调整不是基于零或丢失的级别。
想象一下,您所有的
level
属性都从零开始运行,并且都基于此值并且没有空洞,您只能选择一行levels[index].push({ ...o, children: levels[index + 1] = [] }); // ^^^^^ parent // ^^^^^^^^^ children
使用
o.level
代替index
。然后仅使用
levels
将节点移动到树的正确位置。每个级别取决于之前的(较小)级别。级别不从零开始并且缺少级别的主要问题是将级别调整为有意义的索引。通过使用级别作为值并使用这些值的数组的索引来存档。获取索引的规则是,如果找不到索引,则取数组的最后长度,然后将级别推入
indices
数组。否则,将indices
数组缩短到length
的{{1}}加上一个,以防止在数组中找到更深层的嵌套符号。
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 }, { 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);