Javascript Nested Objects from a String

I have an empty object and a string:

var obj = {}; var str = "abc"; 

Is there any way to turn this into

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

I can't wrap my head around this, and I'm not even sure if this is possible.

+7
source share
5 answers
 var obj = {}; var str = "abc"; 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 = "abc", arr = str.split('.'), obj, o = obj = {}; arr.forEach(key=>{o=o[key]={}}); console.log(obj); 

ES6 / Reduced (without array storage):

 let str = "abc", obj, o = obj = {}; str.split('.').forEach(key=>o=o[key]={}); console.log(obj); 

ES6 / Array.prototype.reduce:

 let str = "abc", last; let obj = str.split('.').reduce((o, val) => { if (typeof last == 'object') last = last[val] = {}; else last = o[val] = {}; return o; }, {}); console.log(obj); 
+8
source

This is from the yui2 yahoo.js file.

 YAHOO.namespace = function() { var a=arguments, o=null, i, j, d; for (i=0; i<a.length; i=i+1) { d=(""+a[i]).split("."); o=YAHOO; // YAHOO is implied, so it is ignored if it is included for (j=(d[0] == "YAHOO") ? 1 : 0; j<d.length; j=j+1) { o[d[j]]=o[d[j]] || {}; o=o[d[j]]; } } return o; }; 

See source of documentation.

https://github.com/yui/yui2/blob/master/src/yahoo/js/YAHOO.js

+3
source

This recursive function returns you a string representation of the desired object.

 //Usage: getObjectAsString('abc'.split(/\./)) function getObjectAsString (array){ return !array.length ? '{}' : '{"' + array[0] + '":' + getObjectAsString (array.slice(1)) + '}'; } 

Now you can convert the output of getObjectAsString to an object using

 JSON.parse(getObjectAsString('abc'.split(/\./))) 

EDIT : Removed the Input as a String version because it only works for single-letter subparts in the namespace, for example, asked in question (abc), which is usually not the case.

+3
source

Here you go:

 var string = "abc", array = string.split('.'); JSON.parse("{\"" + array.join('": {\"') + "\": {" +array.map(function () {return '}'}).join('') + "}") 

Example

0
source

Here is my example:

 function ensureKeys(str, obj) { for(var parts = str.split('.'), i=0, l=parts.length, cache=obj; i<l; i++) { if(!cache[parts[i]]) { cache[parts[i]] = {}; } cache = cache[parts[i]]; } return obj; } var obj = {}; ensureKeys('abc', obj); // obj = { a: { b: { c: {} } } } 
0
source

All Articles