Convert a variable to a JSON Value Name

I have a type variable

var column = $(this).attr('class');

Then I need to add this variable as the name of the JSON object, for example:

obj.push({ column : anotherVar });

This outputs a "column" instead of my variable. Which is the easiest way to convert my variable to a useful string in JSON.

+3
source share
1 answer

You must do this in two steps:

var tmp = {}; tmp[column] = anotherVar;
obj.push(tmp);

You can always use []to refer to properties of an object whose names are dynamic, but you cannot use such names in an object literal.

+6
source

Source: https://habr.com/ru/post/1772476/


All Articles