Here is the Json array, Every object has is_parent and parent_id properties,
If and object has children objects then it’s is_parent property is 1 and vice versa.
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},
],
I want to format above json array as below
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 tried to do this by foreach loop inside another foreach loop but it didn’t work