user988300
user988300

Reputation: 63

How to create dynamically named JavaScript object properties?

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?

Upvotes: 6

Views: 17155

Answers (2)

Francisco Paz
Francisco Paz

Reputation: 3

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", ...}

Upvotes: 0

user166390
user166390

Reputation:

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
})

Upvotes: 20

Related Questions