You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
/**
|
|
|
|
|
* 转化数组数据为树形数据
|
|
|
|
|
* @param {Array} flatData 数据数据
|
|
|
|
|
* @param {Object} option 参数
|
|
|
|
|
* @param {String} option.childrenName 子级字段名称
|
|
|
|
|
* @param {String} option.idName ID字段名称
|
|
|
|
|
* @param {String} option.parentIdName 父级ID字段名称
|
|
|
|
|
*/
|
|
|
|
|
export function treeArray(
|
|
|
|
|
flatData: any[],
|
|
|
|
|
{ childrenName = 'children', idName = 'id', parentIdName = 'parentId' } = {},
|
|
|
|
|
): any[] {
|
|
|
|
|
// 循环所有项
|
|
|
|
|
return flatData.filter((father: any) => {
|
|
|
|
|
// 计算每一项的子级数组
|
|
|
|
|
const children = flatData.filter((child: any) => {
|
|
|
|
|
return father[idName] && child[parentIdName] && father[idName] === child[parentIdName];
|
|
|
|
|
});
|
|
|
|
|
// 如果存在子级,则给父级添加一个children属性,并赋值
|
|
|
|
|
if (children && children.length) {
|
|
|
|
|
father[childrenName] = children;
|
|
|
|
|
}
|
|
|
|
|
// 返回第一层
|
|
|
|
|
return father[parentIdName] === 1;
|
|
|
|
|
});
|
|
|
|
|
}
|