0

Is there a function I can import for converting a plain javascript hash/object into a query string?

So, here are the requirements:

  • Cannot be based on jQuery (I need fastboot support)
  • Must support nested objects & arrays.
  • Must be built into Ember framework (no plugins)

I'm not really wanting to have another plugin dependency, since I know this is done internally in Ember.

Update To clarify what I mean by nested: an object with nested array or object properties will convert to the bracket syntax that Rails is familiar with:

{my_values: [1,2]} => ?my_values[]=1&my_values[]=2

{nested: {key: value}} => ?nested[key]=value

demersus
  • 1,185
  • 2
  • 10
  • 24

1 Answers1

0

This would do it:

function toQueryString (obj){
    var result =[];
    for(var i in obj){
        if(obj.hasOwnProperty(i)){
            if(typeof obj[i] === "object") result.push(toQueryString(obj[i]))
            else result.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
        }
    }
    return result.join("&");
}

Example

Edit: added recursion for nested objects

Community
  • 1
  • 1
Will P.
  • 8,437
  • 3
  • 36
  • 45
  • "Must support nested objects & arrays." Not really sure what the asker means, but this solution definitely won't handle nested values. – Dan Prince Dec 20 '16 at 21:30
  • Edited to recurse into nested objects... I'm assuming nested object properties are treated the same as top level properties – Will P. Dec 20 '16 at 21:35
  • Thank you, but i'm looking for a function that exists already in Ember's framework that I could just import. I know Ember makes this conversion internally with the controller & route queryParams object – demersus Dec 20 '16 at 21:46
  • I'm not super familiar with ember but this post would indicate that it is not possible: http://stackoverflow.com/questions/26264233/nested-object-in-queryparams – Will P. Dec 20 '16 at 21:49
  • @Will P. That's interesting. So maybe the nested object isn't a requirement, but the array is. Actually i'm wanting to send a query back to the rails api, so this isn't used in Ember's queryParams object. Maybe the function doesn't exist in the framework. In that case, i'll have to write my own... – demersus Dec 20 '16 at 21:53