1

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.

Bharata
  • 13,509
  • 6
  • 36
  • 50
NotUser9123
  • 143
  • 1
  • 1
  • 9

1 Answers1

5

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209