Reputation: 55
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
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