Created
February 10, 2015 18:11
-
-
Save cdeutsch/bfac8f8ccd1c678e30ed to your computer and use it in GitHub Desktop.
Replacement for Sugar Object.objectToQueryString that doesn't lose data
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
| var yourApp = {}; | |
| yourApp.objectToQueryString = function(obj, base) { | |
| var tmp; | |
| // If a custom toString exists bail here and use that instead | |
| if(Object.isArray(obj) || (Object.isObject(obj) && obj.toString === Object.prototype.toString)) { | |
| tmp = []; | |
| yourApp.iterateOverObject(obj, function(key, value) { | |
| if(base) { | |
| key = base + '[' + key + ']'; | |
| } | |
| tmp.push(yourApp.objectToQueryString(value, key)); | |
| }); | |
| return tmp.join('&'); | |
| } else { | |
| if(!base) return ''; | |
| return yourApp.sanitizeURIComponent(base) + '=' + (Object.isDate(obj) ? obj.getTime() : yourApp.sanitizeURIComponent(obj)); | |
| } | |
| } | |
| yourApp.iterateOverObject = function(obj, fn) { | |
| var key; | |
| for(key in obj) { | |
| if(!obj.hasOwnProperty(key)) continue; | |
| if(fn.call(obj, key, obj[key], obj) === false) break; | |
| } | |
| } | |
| yourApp.sanitizeURIComponent = function(obj) { | |
| // undefined, null, and NaN are represented as a blank string, | |
| // while false and 0 are stringified. "+" is allowed in query string | |
| return !obj && obj !== false && obj !== 0 ? '' : encodeURIComponent(obj); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment