Function to Serialize JS objects in Query String Parameters
See original GitHub issueThis is in reference to this line in the code:
o.data = Object.keys(o.data).map(function(key){ return key + "=" + encodeURIComponent(o.data[key]); }).join("&");
I just noticed that there is a very helpful utility function nested in ‘fetch’ that is not testable and not reusable even though it has pretty generic functionality (serializing objects into Query String params.)
Thoughts on moving this functionality into it’s own utility method that is testable and reusable?
Lastly, I can make a pull request if necessary but I would suggest adding encodeURIComponent to the ‘key’ variable as well because JavaScript allows characters in object keys that need to be encoded in order to be valid query parameter keys. e.g. var params = { "tom & jerry": "friends" };
Issue Analytics
- State:
- Created 8 years ago
- Comments:9 (5 by maintainers)
URLSearchParams is useful if you want to manipulate a query string (probably intended for usage pushState and similar), but not as much if you want to build them from scratch from object literals.
set
only takes strings, so if you pass objects, arrays or other URLSearchParams it will convert them to strings (“[Object object]”). So it won’t work with nested data structures, and for objects that aren’t nested something like this is easier:Object.entries(data).map(pair => pair.map(encodeURIComponent).join('=')).join('&')
@friday well, I don’t use query-string for that, I use that for query-string 😃