-5

How to divide a string into an object by '.' ?

'a.b.c'

to:

{
    a: {
        b: {
            c: {}
        }
    }
}
Jerry
  • 3
  • 2
  • Does this answer your question? [How do I split a string, breaking at a particular character?](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – Russ J Mar 04 '21 at 03:05

2 Answers2

1

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

const input = 'a.b.c';

const res = input.split('.').reverse().reduce((acc, cur)=>{
  const _acc = {};
  _acc[cur] = acc;
  return _acc;
}, {});

console.log(res);
kyun
  • 9,710
  • 9
  • 31
  • 66