Skip to content

Instantly share code, notes, and snippets.

@twmulloy
Created April 9, 2015 00:49
Show Gist options
  • Save twmulloy/e35ebcfbdfd2488f571b to your computer and use it in GitHub Desktop.
Save twmulloy/e35ebcfbdfd2488f571b to your computer and use it in GitHub Desktop.
JSON flatten to nested form fields
## JSON to nested form data, reset `form` before using
## Formats to `fields` requirement from `ng-file-upload`
## https://github.com/danialfarid/ng-file-upload/wiki/Rails-Example#rails-4-and-angular-file-upload-3-
form = {}
## {"test": { "sup": "bro" }} => { "test[sup]": "bro" }
json2form = (obj, root) ->
angular.forEach obj, (v, k) ->
key = if root then "#{root}[#{k}]" else k
if angular.isObject(v)
json2form(v, key)
else
form[key] = v
## Convert payload keys to nested form fields
json2form(payload, 'item')
console.log form
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment