登录
推荐 文章 Go 技术 课程 下载 专题 AI
首页 >  文章 >  前端

如何为嵌套的问答 JSON 结构自动生成唯一层级 ID

时间:2026-08-20 17:01:33 232浏览 收藏

本文介绍一种基于递归的 TypeScript 方法,为具有双向嵌套关系(QuestionModel 与 ResponseModel 互相引用)的 JSON 数据自动添加符合路径语义的 id 字段,确保每个节点 ID 唯一、可读且反映其在树中的完整位置。

如何为嵌套的问答 JSON 结构自动生成唯一层级 ID

这段内容要讲的,其实是一种基于递归的 TypeScript 处理思路:针对存在双向嵌套关系的 JSON 数据——也就是 QuestionModelResponseModel 相互引用的这类结构——自动补充带有路径语义的 id 字段。这样处理之后,每个节点的 ID 不仅能保持唯一,还具备较好的可读性,同时能够清晰表达它在整棵树中的完整位置。

在搭建动态问答流程时——比如多级表单、决策树,或者对话系统——通常都得给每个问题(QuestionModel)和答案选项(ResponseModel)配上唯一标识符。这样做的作用很直接:前端便于管理状态,后端便于存储数据,后续分析追踪也更顺手。问题在于,这两类对象往往是层层嵌套的:QuestionModel 里包含 responses 数组,而 ResponseModel 里又可能继续包含 questions 数组。正因为结构不是平铺的,ID 就不能只求“唯一”,还得把完整的祖先路径一并体现出来,比如 "yourdestination?_USA_doyouha vea visa?_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));
}
};

使用示例:

const tree: QuestionModel = {
label: "your destination?",
responses: [
{
label: "USA",
questions: [
{
label: "do you ha ve a visa?",
responses: [{ label: "yes" }, { label: "no" }]
}
]
},
{
label: "Canada",
questions: [
{
label: "do you ha ve 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,显著提升嵌套结构的数据可操作性与可追溯性。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>