Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string value to object property name [duplicate]

Tags:

javascript

Possible Duplicate:
How to convert string as object's field name in javascript

I can do this:

var objPosition = {};
objPosition.title = "whatever";

But I'm getting 'title' dynamically, and want to use about a half dozen strings so obtained to assign the half dozen properties to the object. I've tried eval and several other schemes that seem to have the same problem, but have come up empty so far.

I have:

var txtCol = $(this).text();
txtCol = $.trim(txtCol);

and I want the value of txtCol to be a property name.

Any ideas?

like image 945
Michael Broschat Avatar asked Sep 05 '25 17:09

Michael Broschat


2 Answers

Use ['propname']:

objPosition[txtCol] = "whatever";

Demo: http://jsfiddle.net/hr7XW/

like image 196
mellamokb Avatar answered Sep 07 '25 08:09

mellamokb


use bracket notation: objPosition['title'] = "whatever";

so:

var objPosition = {}, ttl = 'title';
objPosition[ttl] = 'whatever'; 

[edit 11/2019: es20xx]

let objPosition = {};
const ttl = 'title';
// [...]
objPosition = {...objPosition, [ttl]: "whatever"};
console.log(objPosition);
like image 24
KooiInc Avatar answered Sep 07 '25 07:09

KooiInc