<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>将id pid的转成children格式的</title>
</head>
<body>
<script type="text/javascript">
var nodes = [
{id:73, pId:0,treeCode:73, treePCode:0, name: "父节点1"},
{id:7301, pId:73,treeCode:7301, treePCode:73, name: "子节点1"},
{id:73011, pId:7301,treeCode:73011, treePCode:7301, name: "子节点1"},
{id:73012, pId:7301, treeCode:73012, treePCode:7301,name: "子节点1"},
{id:7302, pId:73, treeCode:7302, treePCode:73,name: "子节点1"},
{id:73021, pId:7302,treeCode:73021, treePCode:7302, name: "子节点1"},
{id:73022, pId:7302,treeCode:73022, treePCode:7302, name: "子节点1"}
];
window.onload=function(){
var mm=listToTree(nodes);
console.log(mm)
}
function listToTree(data, options) {
if (data && data.length) {
options = options || {}
let ID_KEY = options.idKey || 'id'
let PARENT_KEY = options.parentKey || 'pId'
let CHILDREN_KEY = options.childrenKey || 'children'
let tree = []
let childrenOf = {}
var item, id, parentId
for (var i = 0, length = data.length; i < length; i++) {
item = data[i]
id = item[ID_KEY]
parentId = item[PARENT_KEY] || 0
// 每行数据都可能存在子类
childrenOf[id] = childrenOf[id] || []
// 初始化子类
item[CHILDREN_KEY] = childrenOf[id]
if (parentId != 0) {
// 初始化其父的子节点
childrenOf[parentId] = childrenOf[parentId] || []
// 把它推到父类下的children
childrenOf[parentId].push(item)
} else {
tree.push(item)
}
}
return tree
} else {
return []
}
}
</script>
</body>
</html>