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.

27 lines
914 B
TypeScript

/**
*
* @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;
});
}