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
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#