
本文介绍一种基于递归的 TypeScript 方法,为具有双向嵌套关系(QuestionModel 与 ResponseModel 互相引用)的 JSON 数据自动添加符合路径语义的 id 字段,确保每个节点 ID 唯一、可读且反映其在树中的完整位置。
本文介绍一种基于递归的 typescript 方法,为具有双向嵌套关系(`questionmodel` 与 `responsemodel` 互相引用)的 json 数据自动添加符合路径语义的 `id` 字段,确保每个节点 id 唯一、可读且反映其在树中的完整位置。
在构建动态问答流程(如多级表单、决策树或对话系统)时,常需为每个问题(QuestionModel)和答案选项(ResponseModel)分配唯一标识符,以便前端状态管理、后端存储或分析追踪。由于两类对象深度嵌套——QuestionModel 包含 responses 数组,而 ResponseModel 又可包含 questions 数组——ID 必须体现完整祖先路径,例如 "yourdestination?_USA_doyouhaveavisa?_yes"。
解决该问题的核心是递归遍历 + 路径累积:从根节点开始,每进入一层子节点,就将当前节点的规范化 label(去除空格等不可用字符)追加到父级 ID 后,并用下划线连接。以下为推荐实现:
type ResponseModel = {
label: string;
questions?: QuestionModel[];
id?: string;
};
type QuestionModel = {
label: string;
responses?: ResponseModel[];
id?: string;
};
const generateIds = (
data: QuestionModel | ResponseModel,
basePath: string = ''
): void => {
// 规范化 label:移除所有空白字符(含换行、制表符),保留字母数字与标点
const safeLabel = data.label.replace(/s+/g, '');
// 构建当前节点 ID:若 basePath 为空则直接使用 safeLabel,否则拼接
data.id = basePath ? `${basePath}_${safeLabel}` : safeLabel;
// 若是 QuestionModel,递归处理其 responses
if ('responses' in data && Array.isArray(data.responses)) {
data.responses.forEach((response) => generateIds(response, data.id));
}
// 若是 ResponseModel,递归处理其 questions
if ('questions' in data && Array.isArray(data.questions)) {
data.questions.forEach((question) => generateIds(question, data.id));
}
};✅ 使用示例:
使用 JSON Schema 验证 JSON 数据,从示例 JSON 生成 schema,并将其转换为 TypeScript 接口、Python 数据类或 Markdown 文档。
const tree: QuestionModel = {
label: "your destination?",
responses: [
{
label: "USA",
questions: [
{
label: "do you have a visa?",
responses: [{ label: "yes" }, { label: "no" }]
}
]
},
{
label: "Canada",
questions: [
{
label: "do you have a work licence?",
responses: [{ label: "yes" }, { label: "no" }]
}
]
}
]
};
generateIds(tree); // 原地修改,自动注入所有 id
console.log(JSON.stringify(tree, null, 2));⚠️ 注意事项:
-
原地修改:该函数直接修改输入对象,如需保留原始数据,请先深拷贝(例如使用
structuredClone()或JSON.parse(JSON.stringify()))。 -
label 安全性:正则
/\s+/g仅移除空白字符;若label含特殊符号(如/,#,?)可能影响 URL 路由或 CSS 选择器,可根据需要扩展清洗逻辑(如replace(/[^a-zA-Z0-9_]/g, ''))。 -
类型守卫增强:实际项目中可补充
isQuestionModel/isResponseModel类型谓词,提升类型安全与可读性。 - 性能提示:对于超大型树(>10,000 节点),可考虑迭代式 DFS 避免调用栈溢出,但绝大多数问答配置场景递归完全适用。
通过这一简洁递归策略,你无需手动维护层级索引或路径栈,即可全自动、可预测地生成语义化 ID,显著提升嵌套结构的数据可操作性与可追溯性。

















