Last active
May 26, 2018 15:41
-
-
Save giscafer/737645e577d8ba0643798caf9b4dfaca to your computer and use it in GitHub Desktop.
tree data convert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 父子关系的原始数据格式化成树形结构数据 | |
* @param {Array<Object>} data 原始数据 | |
* @return {Array<Object>} 树形结构数据 | |
*/ | |
export function dataToTree(data) { | |
/*tslint:disable*/ | |
let pos = {}, | |
tree = [], | |
i = 0, | |
count = 0, | |
len = data.length; | |
while (data.length !== 0) { | |
let item = data[i]; | |
item['code'] = item['_id'] || item['code']; | |
item['label'] = item['name'] || '未命名'; | |
item['data'] = item['code']; | |
if (item.parentId == -1 || !item.parentId) { | |
item.children = []; | |
tree.push(item); | |
pos[item.code] = [tree.length - 1]; | |
data.splice(i, 1); | |
i--; | |
} else { | |
let posArr = pos[item.parentId]; | |
if (posArr != undefined) { | |
let obj = tree[posArr[0]]; | |
for (let j = 1; j < posArr.length; j++) { | |
obj = obj.children[posArr[j]]; | |
} | |
item.children = []; | |
obj.children.push(item); | |
pos[item.code] = posArr.concat([obj.children.length - 1]); | |
data.splice(i, 1); | |
i--; | |
} | |
} | |
i++; | |
count++; | |
if (i > data.length - 1) { | |
i = 0; | |
} | |
//避免死循环 | |
if (count > len * 5) { | |
return tree; | |
} | |
} | |
/*tslint:ensable*/ | |
return tree; | |
} |
Author
giscafer
commented
May 26, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment