问个数据转换的题目?

新手上路,请多包涵
var chapterTree = {
  name: '总章节',
  children: [
    {
      name: '章节一',
      children: [
        {
          name: '第一节', 
          children: [
            {name: '第一小节'},
            {name: '第二小节'}
          ]
        },
        {name: '第二节'}
      ]
    },
    {
      name: '章节二',
      children: [
        {name: '章节2-1'},
        {name: '章节2-2'}
      ]
    }
  ]
}

function addLabel(tree){
  // TODO
}

const result = addLabel(chapterTree)
console.log(result); // ["总章节", "(1)章节一", "(1.1)第一节", "(1.1.1)第一小节", "(1.1.2)第二小节", "(1.2)第二节", "(2)章节二", "(2.1)章节2-1", "(2.2)章节2-2"]
阅读 1.6k
2 个回答

直接递归

function addLabel(tree){
  function composeIndex(original, current, close = true) {
    let res = ''
    if (original) {
      res = `${original}.` + `${current}`
    } else {
      res = `${current}`
    }
    return close ? `(${res})` : res
  }
  function getTitle(items, result = [], index = '') {
    items.forEach((item, i) => {
      result.push(composeIndex(index, i + 1) + item.name)
      if (item.children) {
        getTitle(item.children, result, composeIndex(index, i + 1, false))
      }
    })
    return result
  }
  return getTitle(tree.children || [], [tree.name])
}
新手上路,请多包涵
function formatData(data) {
    let result = [];
    function work(chapterTree, preLabel) {
        result.push(`${preLabel ? `(${preLabel})` : ''}${chapterTree.name}`);
        if (typeof chapterTree.children === 'object') {
            chapterTree.children.forEach((item, index) => {
                work(item, `${preLabel ? preLabel + '-' : ''}${index + 1}`);
            });
        }
    }
    work(data)
    return result;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题