Convert a namespaced string, value pair to an JavaScript object

Here's a little code snippet that I wrote recently to convert a namespaced string, value into an JavaScript object. i.e. if passed a value ("", 10) the function will return an JavaScript object {foo:{bar:{baz:10}}}.

// @input key = "", 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;

Run this code in JSFiddle:

Veerasundar profile photo

Written by Veerasundar

Veerasundar is a Software Engineer, currently working at Salesforce as a Lead Member of Technical Staff. He has over 16 years of industry experience, building consumer facing web applications. He lives in Chennai, India.

Contact Veerasundar: Email or Twitter