首页 > 编程语言 > 详细

单层数组生成树状结构

时间:2020-11-11 20:09:39      阅读:31      评论:0      收藏:0      [点我收藏+]
let account_subject_list = [
        {
            "subject":"1221",
            "name":"其他应收款",
            "parent":"",
            "id":10
        },
        {
            "subject":"1221.01",
            "name":"单位往来",
            "parent":"1221",
            "id":11
        },
        {
            "subject":"1231.01",
            "name":"其他应收款",
            "parent":"1231",
            "id":15
        },
        {
            "subject":"2221",
            "name":"应交税费",
            "parent":"",
            "id":85
        },
        {
            "subject":"2221.01",
            "name":"增值税",
            "parent":"2221",
            "id":86
        },
        {
            "subject":"2221.01.01",
            "name":"进项税额",
            "parent":"2221.01",
            "id":87
        },
        {
            "subject":"2221.01.02",
            "name":"销项税额",
            
            "parent":"2221.01",
            "id":88
        },
        {
            "subject":"2221.01.02.01",
            "name":"销项税额",
            "parent":"2221.01.02",
            "id":88
        }
    ]

    /**
 * 单层数组生成树状结构
 */
 function getTree(list) {
      const tree = {}
      const arr = []
      list.forEach(item => {
          tree[item.subject] = item
      })
      list.forEach(item => {
          if(!tree[item.parent]){
              arr.push(item)
          } else {
              tree[item.parent].children = tree[item.parent].children || []
              tree[item.parent].children.push(item)
          }
      })
      return arr
  }

const tree = getTree(account_subject_list)

console.log(‘tree‘,tree)

 

单层数组生成树状结构

原文:https://www.cnblogs.com/lijh03/p/13960127.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!