I have a complex json file that I have to handle with TypeScript / Javascript to make it hierarchical, in order to later build a questionnaire. Every entry of the json has a Id (unique), ParentId (0 If root), Text, Description.
My Typescript Interface
export interface Question {
Id: number;
Text: string;
Desc: string;
ParentId: number;
ChildAnswers?: Answer[];
}
export interface Answer {
Id: number;
Text: string;
Desc: string;
ParentId: number;
ChildQuestion?: Question;
}
I can guarantee that when the object is an answer it will only have one child which we can assume to be a question.
Flat Data Example :
[
{
Id: 1,
Text: 'What kind of apple is it?',
Desc: '',
ParentId: 0
},
{
Id: 2,
Text: 'Green Apple',
Desc: '',
ParentId: 1
},
{
Id: 3,
Text: 'Red Apple',
Desc: '',
ParentId: 1
},
{
Id: 4,
Text: 'Purple GMO Apple',
Desc: '',
ParentId: 1
},
{
Id: 5,
Text: 'What is the issue with the apple?',
Desc: '',
ParentId: 2
},
{
Id: 6,
Text: 'Spoiled.',
Desc: '',
ParentId: 5
},
{
Id: 7,
Text: 'Taste Bad.',
Desc: '',
ParentId: 5
},
{
Id: 8,
Text: 'Too Ripe.',
Desc: '',
ParentId: 5
},
{
Id: 9,
Text: 'Is not an apple.',
Desc: '',
ParentId: 5
},
{
Id: 10,
Text: 'The apple was not green.',
Desc: '',
ParentId: 5
},
... So on ...
]
My Goal
{
Id: 1,
Text: 'What kind of apple is it?',
Desc: '',
ParentId: 0,
ChildAnswers: [
{
Id: 2,
Text: 'Green Apple',
Desc: '',
ParentId: 1,
ChildQuestion: {
Id: 5,
Text: 'What is the issue with the apple?',
Desc: '',
ParentId: 2,
ChildAnswers: [
{
Id: 6,
Text: 'Spoiled.',
Desc: '',
ParentId: 5,
... So on ...
},
{
Id: 7,
Text: 'Taste Bad.',
Desc: '',
ParentId: 5,
... So on ...
},
{
Id: 8,
Text: 'Too Ripe.',
Desc: '',
ParentId: 5,
... So on ...
},
{
Id: 9,
Text: 'Is not an apple.',
Desc: '',
ParentId: 5,
... So on ...
},
{
Id: 10,
Text: 'The apple was not green.',
Desc: '',
ParentId: 5,
... So on ...
},
... So on ...
]
}
},
{
Id: 3,
Text: 'Red Apple',
Desc: '',
ParentId: 1,
... So on ...
},
{
Id: 4,
Text: 'Red Apple',
Desc: '',
ParentId: 1,
... So on ...
}
... So on ...
]
}
I'm currently using this list_to_tree function I found here on stackoverflow, I just don't know if how to tell a question and answer apart. Should I just check to see if the length is one for a question or at odd intervals mark it?:
function list_to_tree(list) {
var map = {}, node, roots = [], i;
for (i = 0; i < list.length; i += 1) {
map[list[i].Id] = i; // initialize the map
list[i].Children = []; // initialize the children
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.ParentId !== 0) {
// if you have dangling branches check that map[node.ParentId] exists
list[map[node.ParentId]].Children.push(node);
} else {
roots.push(node);
}
}
return roots;
}