摘要:项目必用的数据结构转换;
1、 list转tree (效率最高的方式)
/**
* json格式转树状结构
* @param {json:json} json数据
* @param {idStr:String} id的字符串
* @param {pidStr:String} parentId的字符串
* @param {chindrenStr:String} children的字符串
* @return {result:Array} 数组
*/
transData(json, idStr, pidStr, chindrenStr) {
const jsonBak = JSON.parse(JSON.stringify(json));
var r = [],
hash = {},
id = idStr,
pid = pidStr,
children = chindrenStr,
i = 0,
j = 0,
len = jsonBak.length;
// 利用对象将数据进行缓存提高检索效率
for (; i < len; i++) {
hash[jsonBak[i][id]] = jsonBak[i];
}
for (; j < len; j++) {
var aVal = jsonBak[j],
hashVP = hash[aVal[pid]];
if (hashVP) {
let isPush = true;
!hashVP[children] && (hashVP[children] = []);
// 如果数据存在重复数据 则不添加 (根据需要添加这段代码)
for (const item of hashVP[children]) {
if (item.id == aVal.id) {
isPush = false;
}
}
isPush === true ? hashVP[children].push(aVal) : "";
} else {
r.push(aVal);
}
}
return r;
},
2、 tree转list
treeToList(tree) {
var list = []; //结果lsit
for (var i in tree) {
var node = tree[i];
if (!node.children) {
node.children = [];
}
if (node.children && node.children.length !== 0) {
list.push(node);
this.toListDF(node.children, list, node.id); //遍历子树,并加入到list中.
} else {
list.push(node);
}
}
return list;
},
toListDF(tree, list, parentId) {
for (var i in tree) {
var node = tree[i];
if (!node.children) {
node.children = [];
}
list.push(node);
//如果有子结点,再遍历子结点
if (node.children && node.children.length !== 0) {
list.push(node.children);
this.toListDF(node.children, list, node.id); //递归
}
}
},