Search code examples
javascriptgeturl

Counterpart to getURLVars() for simplifying vars


I am using this function to scrape my url and build variables from it:

Read a page's GET URL variables and return them as an "associative array." Calling the function while at example.html?foo=asdf&bar=jkls sets map['foo']='asdf' and map['bar']='jkls'

how would I add a for loop so that

foo = map['foo']
bar = map['bar']

?

First solution didn't work.


Solution

  • You can loop through the map like this

    for (var key in map)
    {
        window[key] = map[key];
    }
    

    This would create window[foo] and window[bar], which are the same as window.foo and window.bar, which are the same as foo and bar.

    EDIT: Here are the contents of the body in the test page I'm using. jQuery should be loaded in the head only because I use it to initialize my test and attach a click handler, but the concept of the for loop is not dependent on jQuery. Since I don't have the map coming into me, I am creating it myself when the document loads. From that point, I am looping over the map just as I described and attaching a click handler to a button to test the proper assignment.

        <input type="button" />
    
        <script type="text/javascript" language="javascript">
            $(document).ready(function(){
                /* You don't need to build the map, you should already have it
                var map = new Object();
                map.foo='bar';
                map.test='meh';
                */
    
                // This is the loop from my original post
                for (var key in map)
                {
                    window[key] = map[key];
                }
    
                // This is just a debug handler, you wouldn't need it
                $('input[type="button"]').click(function(){
                    // This is very annoying, but proves that all three methods of access are valid for both variables
                    alert(window['foo']);
                    alert(window.foo);
                    alert(foo);
                    alert(window['test']);
                    alert(window.test);
                    alert(test);
                    return false;
                });
            });
        </script>