Search code examples
javascriptarraysjavascript-objects

JavaScript: Converting a flat array into a tree like structure without using `eval`


I have an array like this ["aaa","aaa","bbb","ccc"].

what I need is convert it into a form like this:

{ "aaa" :
  { "aaa" :
    { "bbb" :
      { "ccc" : 1 }
    }
  }
}

I know eval can do the trick, however is there any prettier solution?

Thank you for reading my post.


Solution

  • Use Array.reduceRight(). On each iteration return an object, with the previous result as the value of the current property:

    const arr = ["aaa","aaa","bbb","ccc"]
    
    const result = arr.reduceRight((r, s) => ({ [s]: r }), 1)
    
    console.log(result)