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?
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 toobject.keywhenkeyExpression = "key", but note the former case takes an expression as the key and the latter an identifier.)Happy coding.
Also, consider using
.map():