const arrTree = [
{
parentId: null,
id: 0,
},
{
parentId: 0,
id: 2,
},
{
parentId: 0,
id: 1,
},
{
parentId: 1,
id: 3,
},
{
parentId: 2,
id: 4,
}
]
function arrToTree(arr) {
if (!Array.isArray(arr) || arr.length === 0) return {}
let root = null
for ( let i = 0
for ( let j = i
if (arr[j].parentId === arr[i].id) {
if (
Array.isArray(arr[i].children)
) {
arr[i].children.push(arr[j])
} else {
arr[i].children = [ arr[j] ]
}
}
}
if ( arr[i].parentId === null ) root = arr[ i ]
}
return root
}
console.log(arrToTree(arrTree))