Last active
December 17, 2015 12:59
-
-
Save alternatex/5613891 to your computer and use it in GitHub Desktop.
URL Object Serialization borrowed from: http://stackoverflow.com/a/9472534
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
| @serialize = (params) -> | |
| pairs = [] | |
| do proc = (object=params, prefix=null) -> | |
| for own key, value of object | |
| if value instanceof Array | |
| for el, i in value | |
| proc(el, if prefix? then "#{prefix}[#{key}][]" else "#{key}[]") | |
| else if value instanceof Object | |
| if prefix? | |
| prefix += "[#{key}]" | |
| else | |
| prefix = key | |
| proc(value, prefix) | |
| else | |
| pairs.push(if prefix? then "#{prefix}[#{key}]=#{value}" else "#{key}=#{value}") | |
| pairs.join('&') |
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
| // borrowed from: http://stackoverflow.com/a/9472534 | |
| function serialize(params){ | |
| var pairs, proc; | |
| pairs = []; | |
| (proc = function(object, prefix) { | |
| var el, i, key, value, _results; | |
| if (object == null) object = params; | |
| if (prefix == null) prefix = null; | |
| _results = []; | |
| for (key in object) { | |
| if (!Object.hasOwnProperty.call(object, key)) continue; | |
| value = object[key]; | |
| if (value instanceof Array) { | |
| _results.push((function() { | |
| var _len, _results2; | |
| _results2 = []; | |
| for (i = 0, _len = value.length; i < _len; i++) { | |
| el = value[i]; | |
| _results2.push(proc(el, prefix != null ? "" + prefix + "[" + key + "][]" : "" + key + "[]")); | |
| } | |
| return _results2; | |
| })()); | |
| } else if (value instanceof Object) { | |
| if (prefix != null) { | |
| prefix += "[" + key + "]"; | |
| } else { | |
| prefix = key; | |
| } | |
| _results.push(proc(value, prefix)); | |
| } else { | |
| _results.push(pairs.push(prefix != null ? "" + prefix + "[" + key + "]=" + value : "" + key + "=" + value)); | |
| } | |
| } | |
| return _results; | |
| })(); | |
| return pairs.join('&'); | |
| }; | |
| // example | |
| serialize({name:123, data: { test: {ui: 123}}}); // -> "name=123&data[test][ui]=123" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment