All checks were successful
Dev Deploy / Explore-Gitea-Actions (push) Successful in 24s
90 lines
2.2 KiB
TypeScript
90 lines
2.2 KiB
TypeScript
// 定义源数据类型
|
|
type SourceRegion = {
|
|
name: string;
|
|
shortCode?: string;
|
|
regions?: SourceRegion[];
|
|
[key: string]: any; // 允许其他自定义属性
|
|
};
|
|
|
|
// 定义目标数据类型
|
|
type TargetRegion = {
|
|
name: string;
|
|
value?: string | number; // 添加 value 字段
|
|
children?: TargetRegion[];
|
|
[key: string]: any;
|
|
};
|
|
|
|
/**
|
|
* 将任意结构的地区数据转换为统一的嵌套结构
|
|
* @param data 源数据数组
|
|
* @param keys 字段映射配置
|
|
* @returns 转换后的数据
|
|
*/
|
|
export function convertRegions(
|
|
data: SourceRegion[],
|
|
keys: {
|
|
nameKey?: string;
|
|
valueKey?: string; // 新增:指定 value 字段
|
|
regionsKey?: string;
|
|
childrenKey?: string;
|
|
} = {}
|
|
): TargetRegion[] {
|
|
const {
|
|
nameKey = 'name',
|
|
valueKey = 'shortCode', // 默认使用 shortCode 作为 value
|
|
regionsKey = 'regions',
|
|
childrenKey = 'children',
|
|
} = keys;
|
|
|
|
return data.map(item => {
|
|
const converted: TargetRegion = {
|
|
name: item[nameKey] as string,
|
|
};
|
|
|
|
// 如果指定了 valueKey 且源数据中存在该字段,则添加 value
|
|
if (valueKey && item[valueKey] !== undefined) {
|
|
converted.value = item[valueKey];
|
|
}
|
|
|
|
if (item[regionsKey]) {
|
|
const children = convertRegions(
|
|
item[regionsKey] as SourceRegion[],
|
|
keys // 传递 keys 以保持配置一致
|
|
);
|
|
if (children.length > 0) {
|
|
converted[childrenKey] = children;
|
|
}
|
|
}
|
|
|
|
return converted;
|
|
});
|
|
}
|
|
|
|
|
|
/***
|
|
* 使用示例
|
|
* regionsData 是原数据
|
|
*
|
|
*
|
|
* const transformed = convertRegions(regionsData, {
|
|
* nameKey: 'name', // 源数据中表示“名称”的字段
|
|
* regionsKey: 'regions', // 源数据中表示“子级区域”的字段
|
|
* childrenKey: 'children' // 输出结构中表示“子级区域”的字段
|
|
* });
|
|
*
|
|
*
|
|
* 输出示例:
|
|
* [
|
|
* {
|
|
* "name": "北京市",
|
|
* "value": "BJ",
|
|
* "children": [
|
|
* {
|
|
* "name": "东城区",
|
|
* "value": "Dongcheng"
|
|
* },
|
|
* // ...
|
|
* ]
|
|
* }
|
|
* ]
|
|
*/ |