Skip to content

Instantly share code, notes, and snippets.

@kaievns
Created July 4, 2011 14:43
Show Gist options
  • Save kaievns/1063414 to your computer and use it in GitHub Desktop.
Save kaievns/1063414 to your computer and use it in GitHub Desktop.
Recursive Object -> Query String in CoffeeScript
#
# 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