在具有 parent 关系的 javascript 中创建面包屑
Create a breadcrumb in javascript with parent relation
我正在尝试显示面包屑样式的标题,其中每个 child 将与多个 parent 相关联
我有这个数据结构
const modelData = {
course: {
id: 'courseUUID1',
chapters: ['12345', '678910'],
title: 'course 1'
},
// Chapters are children of course as you see above in chapters array
chapters: [
{
id: '12345',
sections: ['88999', '9999888'],
title: 'chapter 1'
},
{
id: '678910',
sections: [],
title: 'chapter 2'
}
],
// section is a child of chapters as you see above in array
sections: [
{
id: '88999',
title: 'Section 1'
},
{
id: '9999888',
title: 'Section 2'
}
]
}
如果我只是控制台每个模型的标题,那么最终结果应该是什么样子它应该向我展示这个
课程 -> 标题:课程 1
章节->标题:Course 1 | chapter 1
部分:-> 标题:Course 1 | chapter 1 | section 1
所以进一步解释>>>
每个 child 都应包括其所有后续 parent 的标题。如上例
section
是 chapter
的 child,chapter
是 course
的 child
最外面的 parent 标题不会有任何修改
提前致谢
通常同一章节不会在课程或书中重复。
此代码段基于层次结构,可能有点帮助。
const modelData = [
{ "title" : "Course 1", "id" : "courseUUID1", "children" : [
{ "title" : "Chapter 1", "id" : "12345", "children" : [
{ "title" : "Section 1", "roleId" : "role11", "children" : []},
{ "title" : "Section 2", "roleId" : "role11", "children" : []},
]}
]},
];
let index = {};
function buildIndex(root, children) {
for(var i in children) {
index[children[i].title] = root;
buildIndex(children[i].title, children[i].children);
}
}
buildIndex("Book", modelData);
function getIndex(idx) {
return index[idx] ? getIndex(index[idx]).concat([idx]) : [idx];
}
console.log( getIndex("Section 2") );
//Check Console ["Book", "Course 1", "Chapter 1", "Section 2"]
我正在尝试显示面包屑样式的标题,其中每个 child 将与多个 parent 相关联
我有这个数据结构
const modelData = {
course: {
id: 'courseUUID1',
chapters: ['12345', '678910'],
title: 'course 1'
},
// Chapters are children of course as you see above in chapters array
chapters: [
{
id: '12345',
sections: ['88999', '9999888'],
title: 'chapter 1'
},
{
id: '678910',
sections: [],
title: 'chapter 2'
}
],
// section is a child of chapters as you see above in array
sections: [
{
id: '88999',
title: 'Section 1'
},
{
id: '9999888',
title: 'Section 2'
}
]
}
如果我只是控制台每个模型的标题,那么最终结果应该是什么样子它应该向我展示这个
课程 -> 标题:课程 1
章节->标题:Course 1 | chapter 1
部分:-> 标题:Course 1 | chapter 1 | section 1
所以进一步解释>>>
每个 child 都应包括其所有后续 parent 的标题。如上例
section
是 chapter
的 child,chapter
是 course
最外面的 parent 标题不会有任何修改
提前致谢
通常同一章节不会在课程或书中重复。
此代码段基于层次结构,可能有点帮助。
const modelData = [
{ "title" : "Course 1", "id" : "courseUUID1", "children" : [
{ "title" : "Chapter 1", "id" : "12345", "children" : [
{ "title" : "Section 1", "roleId" : "role11", "children" : []},
{ "title" : "Section 2", "roleId" : "role11", "children" : []},
]}
]},
];
let index = {};
function buildIndex(root, children) {
for(var i in children) {
index[children[i].title] = root;
buildIndex(children[i].title, children[i].children);
}
}
buildIndex("Book", modelData);
function getIndex(idx) {
return index[idx] ? getIndex(index[idx]).concat([idx]) : [idx];
}
console.log( getIndex("Section 2") );
//Check Console ["Book", "Course 1", "Chapter 1", "Section 2"]