平铺转树结构
平铺结构转树结构
方法
// 平铺结构转为树结构 const arrToTree = (arr, pid) => { const res = [] arr.forEach((item) => { if (item[3] === pid) { const children = arrToTree( arr.filter((v) => v[3] !== pid), item[2] ) const currentItem = { name: item[0], value: item[1], id: item[2], pid: item[3], } if (children.length) { res.push({...currentItem, children}) } else { res.push({...currentItem}) } } }) return res }
树结构转平铺
方法
treeToArr = (tree, arr = []) => {
tree.forEach(item => {
arr.push(item)
if (item.children) {
treeToArr(item.children, arr)
}
})
return arr
}
示例
// 树转平铺
const a = [ { name: 'flare', value: null, id: 1, pid: 0, children: [{ name: 'analytics', value: null, id: 2, pid: 1, }, { name: 'animate', value: null, id: 11, pid: 1, children: [{ name: 'Easing', value: 17010, id: 12, pid: 11, }, { name: 'FunctionSequence', value: 5842, id: 13, pid: 11, }], }, { name: 'display', value: null, id: 17, pid: 1, children: [{ name: 'DirtySprite', value: 8833, id: 18, pid: 17, }, { name: 'LineSprite', value: 1732, id: 19, pid: 17, }], }], }, ] treeToArr(a, [])
// 平铺转树
const data = [
['name', 'value', 'id', 'parentId'],
['flare', null, 1, 0],
['analytics', null, 2, 1],
['cluster', null, 3, 2],
['AgglomerativeCluster', 3938, 4, 3],
['CommunityStructure', 3812, 5, 3],
['graph', null, 6, 2],
['BetweennessCentrality', 3534, 7, 3],
['LinkDistance', 5731, 8, 3],
['optimization', null, 9, 2],
['AspectRatioBanker', 7074, 10, 3],
['animate', null, 11, 1],
['Easing', 17010, 12, 11],
['FunctionSequence', 5842, 13, 11],
['data', null, 14, 1],
['DataField', 1759, 15, 14],
['DataSchema', 2165, 16, 14],
['display', null, 17, 1],
['DirtySprite', 8833, 18, 17],
['LineSprite', 1732, 19, 17],
['flex', null, 20, 1],
['FlareVis', 4116, 21, 20],
]
arrToTree(data, 0)