How to divide a string into an object by '.' ?
'a.b.c'
to:
{
a: {
b: {
c: {}
}
}
}
How to divide a string into an object by '.' ?
'a.b.c'
to:
{
a: {
b: {
c: {}
}
}
}
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);
const input = 'a.b.c';
const res = input.split('.').reverse().reduce((acc, cur)=>{
const _acc = {};
_acc[cur] = acc;
return _acc;
}, {});
console.log(res);