1

I am having following sample code

   var obj = { a: {b:1, c:3 }, d :{f:5}}
        var string = "";
        for(var key in obj){
            for(var subkey in obj[key]){
             string += subkey + "="+ obj[key][subkey] + "&";
             //for last iteration "&" should not be added.
         }
    }
   console.log(string);

output is

b=1&c=3&f=5& 

Required Output

b=1&c=3&f=5
karthick
  • 5,998
  • 12
  • 52
  • 90
  • 1
    In this particular case, the easiest thing to do would be to simply take a substring of your output string, to remove the '&'. – Stilltorik May 22 '13 at 09:49
  • If you're using jQuery, let that to jQuery. Don't compose the URL yourself – John Dvorak May 22 '13 at 09:49
  • 1
    If it is for transmitting parameters and this is the final query string, just leave the `&` at the end. It won´t matter. – Amberlamps May 22 '13 at 09:50
  • `string += "&"+subkey + "="+ obj[key][subkey];` and at the end do `... string.substring(1)` – mplungjan May 22 '13 at 09:52
  • Not a contribution to the question but to your case: are you sure your subkeys are unique (e.g. if subkey b in key a there cannot be a subkey b in key d)? – Menno May 22 '13 at 09:59

4 Answers4

9

An alternative approach would be:

var obj = { a: {b:1, c:3 }, d :{f:5}},
  array = [];
for(var key in obj){
  for(var subkey in obj[key]){
    array.push(subkey + "="+ obj[key][subkey]);
  }
}
console.log(array.join('&'));
Rob Johnstone
  • 1,704
  • 9
  • 14
4

If you're creating the query-part of a url, I'd go with the solution provided here: How to create query parameters in Javascript?

If not, just drop the encoding-part :)

Copy of relevant code:

// Usage:
//   var data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };
//   var querystring = EncodeQueryData(data);
// 
function EncodeQueryData(data)
{
   var ret = [];
   for (var d in data)
      ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
   return ret.join("&");
}
Community
  • 1
  • 1
SimonSimCity
  • 6,415
  • 3
  • 39
  • 52
  • You should be able to drop the first encodeURIComponent I should think, unless the field names have non-ascii chars – mplungjan May 22 '13 at 12:17
2

after for loop you can do like: string = string.slice(0,-1)

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
1

For each iterarion append first & except for the first one.

var obj = { a: {b:1, c:3 }, d :{f:5}}
var string = "";
for(var key in obj){
   for(var subkey in obj[key]){
      if(string !== "") string += "&";
      string += subkey + "=" + obj[key][subkey];
    }
}
letiagoalves
  • 11,224
  • 4
  • 40
  • 66