Magda
Magda

Reputation: 55

how to turn an array into an object of objects

I'd like this array:

const myArr = ['lorem', 'ipsum', 'dolor', 'sit', 'amet']

to change into an object that would look like this:

{
  lorem:{
    ipsum:{
       dolor:{
         sit:{
           amet: ''
         }
       }
     }
   }
 }

is there any easy way to do this?

Upvotes: 1

Views: 67

Answers (1)

Aaronius
Aaronius

Reputation: 4953

const result = myArr.reduceRight((accumulator, currentValue) => {
  return {
    [currentValue]: accumulator
  };
}, '');

If you want, you can shorten the syntax:

const result = myArr.reduceRight((accumulator, currentValue) => 
  ({[currentValue]: accumulator}), '');

Upvotes: 1

Related Questions