基础配置项
const treeOptions = {
key_id: 'id' ,
key_parent: 'parentId' ,
key_child: 'children',
empty_children: false
};
方案一
function treeDataTranslate(data, options = treeOptions) {
var tree = []
var temp = {}
for (var i = 0; i < data.length; i++) {
temp[data[i][options.key_id]] = data[i]
}
for (var k = 0; k < data.length; k++) {
if (temp[data[k][options.key_parent]] &&
data[k][options.key_id] !== data[k][options.key_parent]) {
if (!temp[data[k][options.key_parent]][options.key_child]) {
temp[data[k][options.key_parent]][options.key_child] = []
}
temp[data[k][options.key_parent]][options.key_child].push(data[k])
} else {
tree.push(data[k])
}
}
console.log('tree', tree)
return tree
};
方案二
function treeDataTranslate(data, options = treeOptions){
data.forEach(element => {
let parentId = element[treeOptions.key_parent];
if(!!parentId) {
data.forEach(ele => {
if(ele[treeOptions.key_id] == parentId) {
if(!ele[treeOptions.key_child]) {
ele[treeOptions.key_child] = [];
}
ele[treeOptions.key_child].push(element);
}
});
}
});
let tree = data.filter(ele => !ele[treeOptions.key_parent]);
console.log('tree', tree)
return tree;
};
方案三
function treeDataTranslate(data, options = treeOptions) {
const group = {};
data.forEach((item) => {
const parentId = item[treeOptions.key_parent];
if(!group.hasOwnProperty(parentId)) {
group[parentId] = [];
}
group[parentId].push(item);
});
data.forEach((item) => {
var id = item[treeOptions.key_id];
if(group.hasOwnProperty(id)) {
item[treeOptions.key_child] = group[id];
}
});
console.log('group', group)
return group["null"];
}
方案四
/*
* @list 数组对象
* @tree 树形列表
* @parentId 根节点Id值
*/
function treeDataTranslate (list, tree, parentId) {
list.forEach(item => {
// 判断是否为父级菜单
if (item[treeOptions.key_parent] === parentId) {
const child = {
...item,
key: item.key || item[treeOptions.key_id],
children: []
}
// 迭代 list, 找到当前菜单相符合的所有子菜单
treeDataTranslate(list, child.children, item[treeOptions.key_id])
// 删掉不存在 children 值的属性
if (child.children.length <= 0) {
delete child.children
}
// 加入到树中
tree.push(child)
}
})
}