I have a JSON object built from two nested objects, both of which have a label
property. My function checks that, for a given rank n, the array of QuestionModel[]
or ResponseModel[]
does not have equal labels.
type ResponseModel = {
label: string;
questions?: QuestionModel[];
};
export type QuestionModel = {
label: string;
responses?: ResponseModel[];
};
const duplicatedLabel = async (data: QuestionModel[] | ResponseModel[]): Promise<boolean> => {
const labelSet = new Set<string>();
for (let obj of data) {
if (labelSet.has(obj.label)) {
return true;
} else {
labelSet.add(obj.label);
}
if ("questions" in obj) return await duplicatedLabel(obj.questions!);
if ("responses" in obj) return await duplicatedLabel(obj.responses!);
}
return false;
};
For example, this JSON document is poorly constructed, with two equal labels at the same level yes
. The function should return true
, but it doesn't.
[
{
"label": "your destination?",
"responses": [
{
"label": "USA",
"questions": [
{
"label": "do you have a visa?",
"responses": [
{
"label": "yes"
},
{
"label": "yes"
}
]
}
]
},
{
"label": "Canada",
"questions": [
{
"label": "do you have a work licence?",
"responses": [
{
"label": "yes"
},
{
"label": "no"
}
]
}
]
}
]
}
]
The function always returns false
Comments
Post a Comment