createMarkdownArray.js 1.6 KB
Newer Older
D
DCloud_LXH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

function createMarkdownArray(contents = [], childrenName = 'children') {
  const markdownArray = []
  let itemCatch = {}
  for (let index = 0; index < contents.length; index++) {
    const item = contents[index];

    if (itemCatch.parent) {
      if (item.level === itemCatch.level) {
        const child = {
          ...item,
          parent: itemCatch.parent
        };
        itemCatch.parent[childrenName].push(child)
        delete itemCatch.parent
        itemCatch = child
        continue
      } else if (item.level > itemCatch.level) {
        const child = {
          ...item,
          parent: itemCatch
        };
        (itemCatch[childrenName] || (itemCatch[childrenName] = [])).push(child)
        itemCatch = child
      } else {
        const parent = itemCatch.parent
        delete itemCatch.parent
        itemCatch = parent
        index--
        continue
      }
    } else {
      if (typeof itemCatch.level === 'undefined' || item.level === itemCatch.level) {
        itemCatch = item
        markdownArray.push(itemCatch)
      } else {
        const child = {
          ...item,
          parent: itemCatch
        };
        (itemCatch[childrenName] || (itemCatch[childrenName] = [])).push(child)
        itemCatch = child
        continue
      }
    }
  }

  function removeParent(childs = []) {
    childs.forEach(child => {
      if (child.parent) delete child.parent
      if (child[childrenName]) removeParent(child[childrenName])
    })
  }

  // 移除最后一项 parent 节点,防止循环引用报错
  removeParent(markdownArray[markdownArray.length - 1][childrenName])

  return markdownArray
}

module.exports = createMarkdownArray