Convert a namespaced string, value pair to an JavaScript object
// @input key = "foo.bar.baz", value = 10
// @output {foo:{bar:{baz:10}}}
function toHash(key, value){
var parts = key.split('.').reverse(),
i, foo = {}, bar = {};
foo[parts.shift()] = value;
bar = foo;
for(i=0; i<parts.length; i++){
bar = {};
bar[parts[i]] = foo;
foo = bar;
}
return bar;
}
Blog article: http://veerasundar.com/blog/2014/08/convert-string-to-object-javascript/
Written by Veera
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Code
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#