Created
July 4, 2011 14:43
-
-
Save kaievns/1063414 to your computer and use it in GitHub Desktop.
Recursive Object -> Query String in CoffeeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Recursively converts an object into a query string | |
# | |
to_query_string = (data)-> | |
map = (hash, prefix='')-> | |
result = [] | |
for key, value of hash | |
key = if prefix is '' then key else "#{prefix}[#{key}]" | |
if typeof(value) is 'object' | |
if value instanceof Array | |
for v in value | |
result.push(["#{key}[]", v]) | |
else if value # assuming it's an object | |
for entry in map(value, key) | |
result.push(entry) | |
else | |
result.push([key, "#{value}"]) | |
result | |
data = for e in map(data) | |
"#{encodeURIComponent(e[0])}=#{encodeURIComponent(e[1])}" | |
data.join('&') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment