Files
rustfs-console/utils/array.ts
T
overtrue 6254a8c489 docs: translate all Chinese comments and documentation to English
- Translate Chinese comments in Vue components
- Translate Chinese comments in composables
- Translate Chinese comments in utils and lib modules
- Translate Chinese comments in store modules
- Translate documentation strings in config-helpers.ts
- Maintain code accuracy and readability
2025-10-31 23:03:04 +08:00

36 lines
1.2 KiB
TypeScript

/**
* Convert the given array to a tree structure.
* @param arr - Original array where each element contains id and pid properties, pid represents parent id.
* @returns Returns the converted tree structure array.
*/
export function arrayToTree(arr: any[]) {
// Initialize result array
const res: any = [];
// Use Map to store array elements, with id as key and element itself as value
const map = new Map();
// Traverse array and store each element in Map with id as key
arr.forEach(item => {
map.set(item.id, item);
});
// Traverse array again to organize elements into tree structure based on pid
arr.forEach(item => {
// Get parent element of current element
const parent = item.pid && map.get(item.pid);
// If parent exists
if (parent) {
// If parent already has children, append current element to children array
if (parent?.children) parent.children.push(item);
// If parent has no children, create children array and add current element as first child
else parent.children = [item];
}
// If no parent, add current element directly to result array
else {
res.push(item);
}
});
// Return organized tree structure array
return res;
}