1

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))
3
  • 3
    What have you tried so far? Please add a minimal reproducible example of that effort Commented Aug 23, 2021 at 13:57
  • Hello, added my try. It's not working it's just an idea Commented Aug 23, 2021 at 14:01
  • Your attempt is not a recursive function? Commented Aug 23, 2021 at 15:22

1 Answer 1

1

You can use reduceRight:

let result = ['A','AA','AAA','AAAA'].reduceRight(
    (children, name) => [{ name, children }], []
).pop(); 
      
console.log(result);

It is a bit of an odd structure, as the children array never has more than one element in it...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.