In the given JSON array, each object contains properties 'is_parent' and 'parent_id'. If an object has children objects, its 'is_parent' property is set to 1, otherwise it is set to 0.
let list = [
{id: 4, name: 'dd', is_parent: 1, parent_id: 0},
/**/{id: 5, name: 'ee', is_parent: 0, parent_id: 4},
/**/{id: 6, name: 'ff', is_parent: 1, parent_id: 5},
/**//**/{id: 7, name: 'gg', is_parent: 0, parent_id: 6},
{id: 8, name: 'hh', is_parent: 1, parent_id: 0},
/**/{id: 9, name: 'ii', is_parent: 0, parent_id: 8},
{id: 10, name: 'jj', is_parent: 1, parent_id: 0},
/**/{id: 11, name: 'kk', is_parent: 1, parent_id: 10},
/**//**/{id: 12, name: 'll', is_parent: 1, parent_id: 11},
/**//**//**/{id: 13, name: 'mm', is_parent: 0, parent_id: 12},
],
The desired format of the above JSON array is as follows:
let array = [
{
id: 4,
name: 'dd',
is_parent: 1,
parent_id: 0,
children: [
{id: 5, name: 'ee', is_parent: 0, parent_id: 4},
{
id: 6,
name: 'ff',
is_parent: 1,
parent_id: 5,
children: [
{id: 7, name: 'gg', is_parent: 0, parent_id: 6}
]
}
]
},
{
id: 8,
name: 'hh',
is_parent: 1,
parent_id: 0,
children: [
{id: 9, name: 'ii', is_parent: 0, parent_id: 8}
]
},
{
id: 10,
name: 'jj',
is_parent: 1,
parent_id: 0,
children: [
{
id: 11,
name: 'kk',
is_parent: 1,
parent_id: 10,
children: [
{
id: 12,
name: 'll',
is_parent: 1,
parent_id: 11,
children: [
{id: 13, name: 'mm', is_parent: 0, parent_id: 12}
]
}
]
}
]
},
]
I attempted to achieve this using nested foreach loops, but encountered issues with the implementation.