简体   繁体   中英

Create a breadcrumb in javascript with parent relation

I'm trying to show a breadcrumb style title where each child would be associated with multiple parents

I have this data structure

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'
    }
  ]
}

So what the end result should look like if I just console titles of each model it should show me this

Course -> title: Course 1
Chapter-> title: Course 1 | chapter 1 Course 1 | chapter 1
section: -> title: Course 1 | chapter 1 | section 1 Course 1 | chapter 1 | section 1

So to explain this further >>> each child should include the title of all of its subsequent parents. as in the example above the section is a child of chapter and chapter is a child of course

the outer most parent will have no modifications in title

Thanks in advance

Normally same chapter not repeating in course or book.

This snippet based hierarchy wise, maybe bit helpful.

 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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM