Last Updated: February 25, 2016
·
429
· vraa

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/