treeData.js 2.05 KB
/**
 * 规范化树形数据为统一结构 {label, value, children}。
 *
 * - 从 labelKeys/valueKeys 中按顺序取第一个存在的字段作为 label/value。
 * - 从 childrenKeys 中按顺序取第一个为数组的字段作为 children,并递归处理。
 * - 当某字段不存在时,label/value 会回退为空字符串,children 回退为空数组。
 *
 * @typedef {object} NormalizedNode
 * @property {string} label 标签文本
 * @property {any} value 节点值(可能为字符串、数字等)
 * @property {NormalizedNode[]} children 子节点列表
 * @property {boolean} [leaf] 当原始项无子节点字段时为 false
 *
 * @param {Array<Record<string, any>>} data 输入的树形数据数组
 * @param {object} [options] 可选配置
 * @param {string[]} [options.labelKeys] 候选标签字段顺序
 * @param {string[]} [options.valueKeys] 候选值字段顺序
 * @param {string[]} [options.childrenKeys] 候选子节点字段顺序
 * @returns {NormalizedNode[]} 规范化后的树数据
 */
export function normalizeTree(
	data,
	{
		labelKeys,
		valueKeys,
		childrenKeys,
		outputKeys,
	} = {
		labelKeys: ["label", "name", "title", "defineName", "itemName"],
		valueKeys: ["value", "id", "deptId", "itemId"],
		childrenKeys: ["children", "nodes", "childrenList", "itemList"],
		outputKeys: {
			label: "label",
			value: "value",
			children: "children",
		},
	},
) {
	if (!Array.isArray(data))
		return [];

	return data.map((item) => {
		const label = labelKeys.find(k => item[k] != null);
		const value = valueKeys.find(k => item[k] != null);
		const childrenKey = childrenKeys.find(k => Array.isArray(item[k]));

		const next = { ...item };
		if (!(outputKeys.label in next))
			next[outputKeys.label] = label ? item[label] : "";
		if (!(outputKeys.value in next))
			next[outputKeys.value] = value ? item[value] : "";
		if (childrenKey) {
			next[outputKeys.children] = normalizeTree(item[childrenKey], {
				labelKeys,
				valueKeys,
				childrenKeys,
				outputKeys,
			});
		} else if (!("leaf" in next)) {
			next.leaf = false;
		}
		return next;
	});
}