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