Rafalages
Rafalages

Reputation: 1426

How to use a variable as a json atribute?

Hello im working in a generic function that sends an ajax request according with the selection made:

$('#selectAcao, #selectAno').change(function(){
    var sthis = $(this);
    var sthisTipo = sthis.attr('rel');
    var sthisName = sthis.attr('name');
    var params = {
        "tipo": sthisTipo,
        sthisName : sthis.children('option:selected').val(),
        "atualiza" : true
    }
    $.atualizaSelect(params);
});

All I want is pass a "sthisName" variable as a property in "param":

    var params = {
        "tipo": sthisTipo,
        sthisName : sthis.children('option:selected').val(),
        "atualiza" : true
    }

how can i do this?

Upvotes: 0

Views: 693

Answers (1)

Quentin
Quentin

Reputation: 943569

That isn't JSON. JSON is a data serialisation format. What you have is a JavaScript object literal.

There is no way to define a property name using a variable at creation time for a JavaScript object.

You have to create the object first, and then add the property.

var myObject = {};
myObject[string_containing_property_name] = some_value;

Upvotes: 4

Related Questions