<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function translateDataToTree(data) {
let parents = data.filter(value => value.parentId == 'undefined' || value.parentId == null)
let children = data.filter(value => value.parentId !== 'undefined' && value.parentId != null)
let translator = (parents, children) => {
parents.forEach((parent) => {
children.forEach((current, index) => {
if (current.parentId === parent.id) {
let temp = JSON.parse(JSON.stringify(children))
temp.splice(index, 1)
translator([current], temp)
typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
}
}
)
}
)
}
translator(parents, children)
return parents
}
/**
* 该方法用于将有父子关系的数组转换成树形结构的数组
* 接收一个具有父子关系的数组作为参数
* 返回一个树形结构的数组
*/
function translateDataToTree(data) {
//没有父节点的数据
let parents = data.filter(value => value.parentId == 'undefined' || value.parentId == null)
//有父节点的数据
let children = data.filter(value => value.parentId !== 'undefined' && value.parentId != null)
//定义转换方法的具体实现
let translator = (parents, children) => {
//遍历父节点数据
parents.forEach((parent) => {
//遍历子节点数据
children.forEach((current, index) => {
//此时找到父节点对应的一个子节点
if (current.parentId === parent.id) {
//对子节点数据进行深复制,这里只支持部分类型的数据深复制,对深复制不了解的童靴可以先去了解下深复制
let temp = JSON.parse(JSON.stringify(children))
//让当前子节点从temp中移除,temp作为新的子节点数据,这里是为了让递归时,子节点的遍历次数更少,如果父子关系的层级越多,越有利
temp.splice(index, 1)
//让当前子节点作为唯一的父节点,去递归查找其对应的子节点
translator([current], temp)
//把找到子节点放入父节点的children属性中
typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
}
}
)
}
)
}
//调用转换方法
translator(parents, children)
//返回最终的结果
return parents
}
</script>
</body>
</html>
---------------------------------------------------------------
/*转化函数*/
function(data, attributes) {
let resData = data;
let tree = [];
for(let i = 0; i < resData.length; i++) {
if(resData[i][attributes.parentId] === attributes.rootId) {
let obj = {
id: resData[i][attributes.id],
title: resData[i][attributes.name],
children: []
};
tree.push(obj);
resData.splice(i, 1);
i--;
}
}
run(tree);
function run(chiArr) {
if(resData.length !== 0) {
for(let i = 0; i < chiArr.length; i++) {
for(let j = 0; j < resData.length; j++) {
if(chiArr[i].id == resData[j][attributes.parentId]) {
let obj = {
id: resData[j][attributes.id],
title: resData[j][attributes.name],
children: []
};
chiArr[i].children.push(obj);
resData.splice(j, 1);
j--;
}
}
run(chiArr[i].children);
}
}
}
return tree;
}
1
var data=[{id:1,parentId:0,name:"测试1"},
1
{id:2,parentId:1,name:"测试2"}]
1
2
3
4
5
<em id="__mceDel"><br>let attributes = { //定义数据属性名称
id: 'id',
parentId: 'parentId',
name: 'groupName',<br>rootId: 0
}<br>/*调用*/<br>formatTreeData(data,attributes);<br></em>