user977433 user977433 - 4 months ago 18
Javascript Question

Javascript nested objects from string

I've got an empty object and a string:

var obj = {};
var str = "a.b.c";


Is there a way I can turn this into

obj = { a: { b: { c: { } } } }


I can't quite wrap my head around this one and I'm not even sure if it would be possible.

Answer
var obj = {};
var str = "a.b.c";
var arr = str.split('.');
var tmp = obj;

for (var i=0,n=arr.length; i<n; i++){
   tmp[arr[i]]={};
   tmp = tmp[arr[i]];
}

ES6:

let str = "a.b.c",
    arr = str.split('.'),
    obj, o = obj = {};

arr.forEach(key=>{o=o[key]={}});

console.log(obj);

ES6/Reduced (array storage unnecessary):

let str = "a.b.c", obj, o = obj = {};

str.split('.').forEach(key=>o=o[key]={});

console.log(obj);