Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  97] [ 5]  / answers: 1 / hits: 65140  / 12 Years ago, wed, january 30, 2013, 12:00:00

I'm fairly new to JavaScript and am not sure this is possible to do but basically I would like to take an object and convert it into an array of strings in the format; array[0] = 'prop1=value1'



The reasoning behind this is that I'm having a user enter a list of k=v pairs into a form, later it's written as an object within a json blob. Going from the key value csl to the json object was simple, now I need to go back the other way (I've received the JSON via an ajax call and want to populate a blank form). Is this possible in JavaScript? If not please offer a reasonable work around.



Sample code;



Object in debugger;



 Object
private_key: private-key
public_key: public-key


I need to convert that to;



 private_key=private-key,public_key=public-key


Basically I need something like this (pseudo code)



var outputString = '';
foreach (prop in obj)
{
outputString = outputString + prop.tostring() + '=' + prop.value + ',';
}

More From » reflection

 Answers
26

You're probably looking for something along the lines of



var obj = {value1: 'prop1', value2: 'prop2', value3: 'prop3'};
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(key + '=' + obj[key]);
}
};
var result = arr.join(',');
alert(result);


Notice that it will work fine if your values are strings; if they're complex objects then you'll need to add more code.



Or you can just use jQuery.param, which does what you want, even for complex types (although it uses the & character as the separator, instead of the comma.


[#80511] Tuesday, January 29, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shawn

Total Points: 507
Total Questions: 103
Total Answers: 111

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
shawn questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Tue, Jun 8, 21, 00:00, 3 Years ago
Sat, Feb 27, 21, 00:00, 3 Years ago
Sat, Dec 19, 20, 00:00, 4 Years ago
Sat, May 9, 20, 00:00, 4 Years ago
;