How to divide a string into an object by ‘.’? [closed]

How to divide a string into an object by ‘.’ ?

'a.b.c'

to:

{
    a: {
        b: {
            c: {}
        }
    }
}

Answer

Split the string by .s, reverse it, and use reduceRight to built it up from the inner parts outward:

const str = 'a.b.c';

const obj = str
  .split('.')
  .reduceRight(
    (innerObj, propName) => ({ [propName]: innerObj }),
    {}
  );
console.log(obj);

Leave a Reply

Your email address will not be published. Required fields are marked *