xxm-test-js
Version:
xxm-js通用js工具(utils)库
84 lines • 2.88 kB
JavaScript
;
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.flattenTree = flattenTree;
/**
* 将树形结构的数据扁平化为数组。
*
* @template T 泛型类型,表示树节点对象的类型,要求是键值对对象。
*
* @param {Array<TreeNode<T>> | TreeNode<T>} tree - 树的根节点或树节点数组。
* @param {FlattenTreeOptions<T>} [options={}] - 配置项,包括节点ID、父节点ID、子节点数组的键名及过滤条件。
*
* @returns {Array<Omit<TreeNode<T>, keyof T>>} 扁平化后的数组,每个元素都是原始树中的一个节点,但不包含子节点属性。
*
* @example
* ```typescript
* // 示例用法
* interface DataItem {
* id: number;
* name: string;
* parentId?: number | null;
* }
*
* const treeData = [
* {
* id: 1,
* name: 'Root',
* parentId: null,
* children: [
* {
* id: 2,
* name: 'Child 1',
* parentId: 1,
* children: [
* { id: 4, name: 'Grandchild 1', parentId: 2 },
* { id: 5, name: 'Grandchild 2', parentId: 2 }
* ]
* },
* { id: 3, name: 'Child 2', parentId: 1 }
* ]
* },
* { id: 6, name: 'Another Root', parentId: null }
* ];
*
* const flatData = flattenTree(treeData, {
* idKey: 'id',
* parentIdKey: 'parentId',
* childrenKey: 'children'
* });
*
* console.log(JSON.stringify(flatData, null, 2));
* ```
*/
function flattenTree(tree, options = {}) {
// Prefix with _ to indicate these are intentionally unused
const { idKey: _idKey = 'id', parentIdKey: _parentIdKey = 'parentId', childrenKey = 'children', filter, } = options;
const result = [];
const stack = Array.isArray(tree) ? [...tree] : [tree];
while (stack.length > 0) {
const node = stack.pop();
if (!filter || filter(node)) {
// 使用解构赋值排除 childrenKey
const _a = node, _b = childrenKey, _ = _a[_b], rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
result.push(rest);
if (node[childrenKey] && Array.isArray(node[childrenKey])) {
for (let i = node[childrenKey].length - 1; i >= 0; i--) {
stack.push(node[childrenKey][i]);
}
}
}
}
return result;
}
//# sourceMappingURL=flattenTree.js.map