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
asked May 22, 2013 at 9:46
karthick
6,19812 gold badges54 silver badges92 bronze badges
4 Answers 4
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('&'));
answered May 22, 2013 at 9:55
Rob Johnstone
1,7249 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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("&");
}
answered May 22, 2013 at 9:57
SimonSimCity
6,5823 gold badges43 silver badges56 bronze badges
1 Comment
mplungjan
You should be able to drop the first encodeURIComponent I should think, unless the field names have non-ascii chars
after for loop you can do like: string = string.slice(0,-1)
answered May 22, 2013 at 9:51
Grijesh Chauhan
58.6k20 gold badges145 silver badges214 bronze badges
4 Comments
mplungjan
Or
string += "&"+subkey + "="+ obj[key][subkey]; and at the end ... string.substring(1)Grijesh Chauhan
@Christoph sorry I commented correct but answered wrong, for mplungjan let me think
Grijesh Chauhan
@mplungjan sorry :( I didn't understand,
string.substring(1) will remove first char if I am not wrong, please example bit more I am also new learner web-languages ..mplungjan
Yes it will, and I moved the & to the start.
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];
}
}
answered May 22, 2013 at 9:50
letiagoalves
11.3k4 gold badges43 silver badges68 bronze badges
Comments
lang-js
&at the end. It won´t matter.string += "&"+subkey + "="+ obj[key][subkey];and at the end do... string.substring(1)