Given the following Array of strings:
['A','AA','AAA','AAAA']
I am trying to convert them to an object like this using a function:
{
name: 'A',
children: [
{
name: 'AA',
children: [
{
name: 'AAA',
children: [
{
name: 'AAAA'
children: []
}
]
}
]
}
]
}
I cannot find a solution that works with recursivity. Any suggestions please?
What i've tried, and it's not working since it's lacking recursivity logic:
array = ['A','AA','AAA','AAAA']
foo(array) {
let resultArray = []
while (array.length > 0) {
const item = array.shift()
resultArray.push({
name: item,
children: array[0]
})
}
return resultArray
}
console.log(foo(array))