我在TypeScript中创建了两个自定义类型。
type ResponseModel = {
label: string;
questions?: QuestionModel[];
id?: string;
};
type QuestionModel = {
label: string;
responses?: ResponseModel[];
id?: string;
};
字符串
从这两种类型中,我构建了一个QuestionModel
JSON文件。
{
"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,以便得到以下结果。
{
"label": "your destination?",
"id": "yourdestination?",
"responses": [
{
"label": "USA",
"id": "yourdestination?_USA",
"questions": [
{
"label": "do you have a visa?",
"id": "yourdestination?_USA_doyouhaveavisa?",
"responses": [
{
"label": "yes",
"id": "yourdestination?_USA_doyouhaveavisa?_yes"
},
{
"label": "no",
"id": "yourdestination?_USA_doyouhaveavisa?_no"
}
]
}
]
},
{
"label": "Canada",
"id": "yourdestination?_Canada",
"questions": [
{
"label": "do you have a work licence?",
"id": "yourdestination?_Canada_doyouhaveaworklicence?",
"responses": [
{
"label": "yes",
"id": "yourdestination?_Canada_doyouhaveaworklicence?_yes"
},
{
"label": "no",
"id": "yourdestination?_Canada_doyouhaveaworklicence?_no"
}
]
}
]
}
]
}
型
我的问题是构建嵌套的id,那么我如何从头到尾按照嵌套的顺序读取对象呢?
1条答案
按热度按时间envsm3lx1#
这只是一个标准的recursive过程:
字符串
Playground链接
对于每个嵌套的问题和回答,使用其父级的ID调用
identify()
函数,identify()
函数将当前标签附加到该ID。