30

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?

0

4 Answers 4

62

Use ['propname']:

objPosition[txtCol] = "whatever";

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

Sign up to request clarification or add additional context in comments.

Comments

15

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

Comments

4

you can also set the object's key like this

var property = "title"
objPosition[property] = "something";

Comments

3

Use the bracket notation like this:

objPosition["title"] = "Whatever";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.