6

Here is what I have

<form>
  <input type="text" name="item1" class="grab" value="userInput" />
  <input type="text" name="somethingelse1" class="grab" value="differentUserInput" />
  ... (any number of inputs)
</form>

Using JQuery/Javascript I want to build an array of objects with name value pairs that looks like this:

output = [ {item1: userInput}, {somethingelse1: differentUserInput} ... etc.];

I have tried this with no success:

var output = new Array();
$('.grab').each( function(index) { 
    output.push({$(this).attr('name'): $(this).val()} );
});

I have tried several variations including experimenting with eval(), but to no avail. If I remove the $(this).attr('name'), and give it a static name it works... so how can I create dynamically named objects?

2 Answers 2

20

The literal-object syntax cannot be used for non-literal keys. To use a non-literal key with an object requires the object[keyExpression] notation, as below. (This is equivalent to object.key when keyExpression = "key", but note the former case takes an expression as the key and the latter an identifier.)

var output = []
$('.grab').each(function(index) { 
    var obj = {}
    obj[$(this).attr('name')] = $(this).val()
    output.push(obj)
})

Happy coding.


Also, consider using .map():

var output = $('.grab').map(function() { 
    var obj = {}
    obj[$(this).attr('name')] = $(this).val()
    return obj
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that worked. Thanks for the quick reply and the good information.
0

I took only the id of the form as a parameter of this function:

function form2JSON(form){
    var info_ser = $('#'+form).serialize();
    var data = info_ser.split('&');
    var output = {};
    $.each( data, function( i, l ){
        var data_input = l.split('=');
        output[data_input[0]] = data_input[1];
    });
   return output;
}

The result object is something like this Object { fieldname="value", fieldname1="value1", fieldname2="value3", ...}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.