JavaScript

您所在的位置:网站首页 js二维数组转换 JavaScript

JavaScript

2023-08-26 20:37| 来源: 网络整理| 查看: 265

arr = [ ["a", "aa", "aaa", "aaaa"], ["b", "bb", "bbb"], ["a", "ab", "aba"], ["a", "aa", "aab"] ]tree = [ { "name":"a", "child":[ { "name":"aa", "child":[ { "name":"aaa", "child":[ { "name":"aaaa", "child":[] } ] }, { "name":"aab", "child":[] } ] }, { "name":"ab", "child":[ { "name":"aba", "child":[] } ] } ] }, { "name":"b", "child":[ { "name":"bb", "child":[ { "name":"bbb", "child":[] } ] } ] } ]

1. 数组转换为树形结构

要点:节点的存储与引用

function ArrToTree(arr) { let result =[] // 结果 let concatStr = "=====" // 连接符(随便写,保证key唯一性就OK) let map = new Map() // 存储根节点 function addList(list) { let path = [] // 路径 let node // 当前节点 list.forEach(v => { path.push(v) let key = path.join(concatStr) let item = { name: v, child: [] } // 当前节点 if(map.has(key)) { item = map.get(key) } else { map.set(key, item) // 存储路径对应的节点 if(node) { node.child = (node.child || []).concat(item) } else { result.push(item) } } node = item // 更新当前节点 }) } arr.forEach(v => addList(v)) return result }

2. 树形结构转换为数组

function TreeToArr(tree) { let result = [] // 结果 function getPath(node, arr) { arr.push(node.name) if(node.child.length > 0) { // 存在多个节点就递归 node.child.forEach(v2 => getPath(v2, [...arr])) } else { result.push(arr) } } tree.forEach(v => getPath(v, [])) return result }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3