Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Variable to JSON Value Name

I have a variable like

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

I then need to add this variable as the name of a JSON object like so

obj.push({ column : anotherVar });

This outputs "column" instead of my variable. What is the easiest way to convert my variable into a usable string in JSON.

like image 227
Mike Avatar asked Nov 21 '25 03:11

Mike


1 Answers

You have to do it in two steps:

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

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

like image 180
Pointy Avatar answered Nov 23 '25 18:11

Pointy