angularjs - How to convert square bracket object keys from URL location into nested object in Javascript? -


with:

var obj = { "object[foo][bar][ya]": 100 }; 

how can create:

var obj = { object: { foo: { bar: { ya: 100 }}}}; 

manual approach

split given string bracket, iterate through resultant tokens make nested object:

given

var obj = { "object[foo][bar][ya]": 100 }; 

split them get

var tokens = object.keys(obj)[0]     .split('[')     .map(function(s){return s.replace(']','')});     // tokens = [ 'object', 'foo', 'bar', 'ya' ] 

then make nested object, inside out

var result = {}; tokens.reverse().foreach(function(key){     if (object.keys(result).length==0){         result[key] = obj[object.keys(obj)[0]]; // inner-most key-value     }     else{         var temp = {};         temp[key] = result;         result = temp;     } }); 

result

{"object":{"foo":{"bar":{"ya":100}}}}


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -