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:


Chat with the Author

This post was written by Veera, a software developer by profession and a maker by passion.

You will be taken to where you can edit the tweet before posting.

If you liked my writing, you may like my products