deploy-ease-platform/frontend/src/components/FormDesigner/utils/pathHelper.ts
2025-11-06 16:10:37 +08:00

103 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 路径转换工具(基于 lodash
* 支持将扁平的表单数据转换为嵌套对象,反之亦然
*
* 支持的路径格式:
* - 点号路径: 'jenkins.serverId' → { jenkins: { serverId: value } }
* - 数组路径: 'users[0].name' → { users: [{ name: value }] }
* - 混合路径: 'company.users[0].profile.email'
* - 简单字段: 'username' → { username: value }
*/
import { set, get } from 'lodash';
/**
* 将扁平的表单数据转换为嵌套对象
* @param formData 扁平的表单数据 { 'jenkins.serverId': 'xxx', 'users[0].name': 'Alice' }
* @returns 嵌套对象 { jenkins: { serverId: 'xxx' }, users: [{ name: 'Alice' }] }
*
* @example
* const flatData = {
* 'jenkins.serverId': 'server-001',
* 'jenkins.url': 'http://jenkins.com',
* 'users[0].name': 'Alice',
* 'users[0].role': 'admin',
* 'description': '测试'
* };
*
* const nestedData = transformToNestedObject(flatData);
* // {
* // jenkins: { serverId: 'server-001', url: 'http://jenkins.com' },
* // users: [{ name: 'Alice', role: 'admin' }],
* // description: '测试'
* // }
*/
export function transformToNestedObject(formData: Record<string, any>): Record<string, any> {
const result: Record<string, any> = {};
Object.keys(formData).forEach(fieldName => {
const value = formData[fieldName];
// 跳过 undefined 的值
if (value !== undefined) {
// lodash.set 自动处理所有路径格式
set(result, fieldName, value);
}
});
return result;
}
/**
* 从嵌套对象中提取值(用于表单回显)
* @param nestedData 后端返回的嵌套数据
* @param fieldNames 字段名列表
* @returns 扁平的表单数据
*
* @example
* const nestedData = {
* jenkins: { serverId: 'server-001', url: 'http://jenkins.com' },
* users: [{ name: 'Alice', role: 'admin' }]
* };
*
* const fieldNames = [
* 'jenkins.serverId',
* 'jenkins.url',
* 'users[0].name',
* 'users[0].role'
* ];
*
* const flatData = transformToFlatObject(nestedData, fieldNames);
* // {
* // 'jenkins.serverId': 'server-001',
* // 'jenkins.url': 'http://jenkins.com',
* // 'users[0].name': 'Alice',
* // 'users[0].role': 'admin'
* // }
*/
export function transformToFlatObject(
nestedData: Record<string, any>,
fieldNames: string[]
): Record<string, any> {
const result: Record<string, any> = {};
fieldNames.forEach(fieldName => {
const value = get(nestedData, fieldName);
if (value !== undefined) {
result[fieldName] = value;
}
});
return result;
}
/**
* 检查路径是否包含嵌套(点号或中括号)
* @param path 路径字符串
* @returns 是否是嵌套路径
*/
export function isNestedPath(path: string): boolean {
return path.includes('.') || path.includes('[');
}