0

I have a string: 'lorem,ipsum,dolor,sit,amet' And I want to write a function with a parameter that converts this string passed as a parameter to an object like this:

{
     lorem:{
       ipsum:{
         dolor:{
           sit:{
             amet: []
           }
         }
       }
     }
 }
1

1 Answer 1

2

Split the string, and use Array.reduceRight() to generate the object:

const fn = (str, param) =>
  str.split(',')
   .reduceRight((acc, key) => ({ [key]: acc }), param)

const str = 'lorem,ipsum,dolor,sit,amet'

const result = fn(str, [])

console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.