views:

46

answers:

3

I need to pass a few serialized form elements into a function to return them as a JSON object. I wrote the function, but fieldName ends up in the json object as "fieldName" instead of the actual field name ie; "PositionId", or "Series". The values however are correct. JS will not allow me to use field.name, but it does allow field.value, thats why I had to create var fieldName. Here is the function:

function SerializedFormToJSON(serializedForm){
   var myJSONObject = {};
   var fieldName = "";
   $.each(serializedForm, function(i, field) {
      fieldName = field.name;
      if (field.value != "" && field.value != "ALL") {
        myJSONObject = { fieldName: field.value };
      }
   });
return myJSONObject;
}
+3  A: 

Besides the problem you are experiencing, you're recreating the object in every iteration of the loop. The line where you set the property should read:

myJSONObject[fieldName] = field.Value;

Complete function:

function SerializedFormToJSON(serializedForm){
   var myJSONObject = {};
   var fieldName = "";
   $.each(serializedForm, function(i, field) {
      fieldName = field.name;
      if (field.value != "" && field.value != "ALL") {
        myJSONObject[fieldName] =  field.value;
      }
   });
return myJSONObject;
Philippe Leybaert
darn, you beat me by like 10 seconds.
CookieOfFortune
No, you would want it to be an object, not an array.
Bobby Eickhoff
was a typo :) fixed
Philippe Leybaert
A: 
myJSONObject[fieldName] = field.value;
CookieOfFortune
A: 

Try using array subscript notation:

myJSONObject[fieldName] = field.value;
Bobby Eickhoff