I have an array like the below.
[{
id: 1,
is_child_question: false,
parent_question_id: null },
{
id: 2,
is_child_question: true,
parent_question_id: 1},
{
id: 3,
is_child_question: true,
parent_question_id: 2}]
I want to iterate it and create a new array like below.
[{
id: 1,
is_child_question: false,
parent_question_id: null,
children: [{
id: 2,
is_child_question: true,
parent_question_id: 1,
children:[{
id: 3,
is_child_question: true,
parent_question_id: 2,
}]
}]
}]
Like a tree.
While iterating if the node has is_child_question === true
it should go under its parent node.
You could take a single loop approach with an object for collecting objects with id
as key.
var data = [{ id: 3, is_child_question: true, parent_question_id: 2 }, { id: 2, is_child_question: true, parent_question_id: 1 }, { id: 1, is_child_question: false, parent_question_id: null }],
tree = data.reduce((r, o) => {
o.children = r[o.id] && r[o.id].children;
r[o.id] = o;
r[o.parent_question_id] = r[o.parent_question_id] || {};
r[o.parent_question_id].children = r[o.parent_question_id].children || [];
r[o.parent_question_id].children.push(o);
return r;
}, {}).null.children;
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }