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
  • 12,657
  • 6
  • 32
  • 48
NotUser9123
  • 143
  • 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
  • 166,183
  • 27
  • 198
  • 186