Created
October 21, 2016 10:12
-
-
Save tkizm1/cd63c10ac8f669caa7b0a49bf47e8b52 to your computer and use it in GitHub Desktop.
normal array to angular-ui-tree
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> | |
</head> | |
<body> | |
<script> | |
var result = [ | |
{"id": 1,"title": "node1","father_node":null}, | |
{"id": 2,"title": "node1","father_node":1}, | |
//{"id": 3,"title": "node1","father_node":1}, | |
{"id": 4,"title": "node1","father_node":null}, | |
{"id": 5,"title": "node1","father_node":4}, | |
//{"id": 6,"title": "node1","father_node":4}, | |
]; | |
var target = [];// 目标数据 | |
for (var i in result) { | |
// 遍历数组,每一个单独处理 | |
console.log(result[i]); | |
if(result[i]['father_node']===null)//如果没有上层节点,那么直接把数据放到target | |
target.push(result[i]); | |
else{ | |
// 如果有上层节点 | |
var father = target.filter( | |
function(obj){ | |
return obj.id === result[i]['father_node']; | |
} | |
)[0];// 目标节点的id 等于 当前节点的father_node 根据这个条件去查找 | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | |
if(target[target.indexOf(father)]['nodes']===undefined){ | |
// 如果父节点的nodes为空,那么用数组初始化 | |
target[target.indexOf(father)]['nodes']=[]; | |
} | |
target[target.indexOf(father)]['nodes'].push(result[i]); | |
// 初始化必定已经完成,那么只需要把目标数据放在 上层节点的nodes里 | |
} | |
//console.log(target); | |
// 打印结果 | |
console.log(JSON.stringify(target,null, 4)); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment