如何使用JavaScript将冒号分隔的权限Code转为指定树形结构
JavaScript平级权限数组转树形结构实现
核心逻辑
- 遍历所有权限项,将每个权限的
code字段按冒号:拆分为分层的文本数组 - 从根层级开始逐层匹配节点,同层级不存在对应文本的节点则新建,已存在则直接复用
- 仅非最末层级的节点添加
children属性,最末操作节点不需要子属性
完整实现代码
// 示例原始权限数组 const author = [ { id: '1', code: 'ghj:aws:aws_vpc:create', description: 'Permission to create', status: 'ACTIVE', scope: 'PROVIDER' }, { id: '2', code: 'ghj:aws:aws_vpc:update', description: 'Permission to create', status: 'ACTIVE', scope: 'PROVIDER' }, { id: '3', code: 'ghj:aa:aa:update', description: 'Permission', status: 'ACTIVE', scope: 'PROVIDER' }, { id: '4', code: 'dusk:resource-management:compute:ip:list', description: 'Permission', status: 'ACTIVE', scope: 'PROVIDER' }, { id: '5', code: 'dusk:resource-management:storage:disk:delete', description: 'Permission', status: 'ACTIVE', scope: 'PROVIDER' }, { id: '6', code: 'dusk:resource-management:storage:disk:Update', description: 'Permission', status: 'ACTIVE', scope: 'PROVIDER' } ] // 转换函数 function buildPermissionTree(permissions) { const resultTree = [] permissions.forEach(permission => { // 拆分code为层级列表 const levelList = permission.code.split(':') // 当前遍历层级的节点列表 let currentNodes = resultTree levelList.forEach((text, index) => { // 查找当前层级是否存在匹配节点 let matchNode = currentNodes.find(node => node.text === text) if (!matchNode) { matchNode = { text } // 非最后一层新增children属性 if (index !== levelList.length - 1) { matchNode.children = [] } currentNodes.push(matchNode) } // 进入下一层级遍历 currentNodes = matchNode.children || [] }) }) return resultTree } // 调用示例 const tree = buildPermissionTree(author) console.log(tree)
可选适配
如果你只需要ghj开头的权限树(和你给出的示例输出完全一致),可以在遍历前加过滤逻辑:
// 只处理ghj开头的权限 const filteredPermissions = author.filter(item => item.code.startsWith('ghj')) const tree = buildPermissionTree(filteredPermissions)
注:代码严格区分大小写,
update和Update会被识别为两个不同节点,和你的需求匹配。
内容的提问来源于stack exchange,提问作者Nandhini Anand
相关产品推荐
相关产品推荐

