树形数组结构字段转换

一般而言,tree组件中要求的的数据为

let tree = [
    {
        title: 'parent-1',
        expand: true,
        children: [
            {
              title: 'child-1',
              expand: true
            }    
        ] 
     },
    {
      title: 'parent-2',
      expand: true,
      children: [
        {
          title: 'child-2',
          expand: true
        }
      ]
    }
]

可是大多数时候,数据是后台返回的,前端需要根据后台返回的字段进行动态渲染,这就需要做一个映射转换了,方法如下:

const convertTree = (tree) => {
        const result = []
        tree.forEach((item) => {
          let children = item.children || []
          let expand = true
          // 利用解构赋值的方式进行转换
          let {
            chapterName: title
          } = item
          if (children && children.length) {
            children = convertTree(children)
          }
          result.push({
            title,
            children,
            expand
          })
        })
        return result
 }

转换后,就能得到想要的字段啦!!!

posted @ 2020-01-10 15:30  Max1991  阅读(367)  评论(0)    收藏  举报