如何为嵌套的TypeScript类型JSON生成层级ID?
解决方案:递归遍历生成嵌套层级ID
由于你的数据结构是Question与Response互相嵌套的递归结构,最适合用递归函数遍历每个节点,同时传递父级ID来拼接当前节点的ID。
实现步骤
- 先写一个工具函数,移除label中的空格:
const removeSpaces = (str: string): string => str.replace(/\s+/g, '');
- 编写递归处理函数,分别处理
QuestionModel和ResponseModel,传递父级ID作为参数:
// 处理单个Question function processQuestion(question: QuestionModel, parentId?: string): QuestionModel { // 生成当前Question的ID:有父ID则拼接,无父ID直接用去空格的label const currentId = parentId ? `${parentId}_${removeSpaces(question.label)}` : removeSpaces(question.label); const processedQuestion = { ...question, id: currentId }; // 递归处理子Response if (processedQuestion.responses) { processedQuestion.responses = processedQuestion.responses.map(response => processResponse(response, currentId) ); } return processedQuestion; } // 处理单个Response function processResponse(response: ResponseModel, parentId: string): ResponseModel { // 生成当前Response的ID:父ID拼接去空格的label const currentId = `${parentId}_${removeSpaces(response.label)}`; const processedResponse = { ...response, id: currentId }; // 递归处理子Question if (processedResponse.questions) { processedResponse.questions = processedResponse.questions.map(question => processQuestion(question, currentId) ); } return processedResponse; }
- 使用示例:
// 原始数据 const originalData: 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" } ] } ] } ] }; // 生成带层级ID的结果 const result = processQuestion(originalData); console.log(JSON.stringify(result, null, 2));
逻辑说明
- 递归函数会逐层遍历所有节点:从根Question开始,生成ID后遍历其下的Response,给每个Response生成ID后再遍历其下的Question,完全匹配嵌套结构。
- 自动处理可选属性:如果
responses或questions不存在,会直接跳过,避免报错。
内容的提问来源于stack exchange,提问作者DONGMO BERNARD GERAUD
相关产品推荐
相关产品推荐

