Convert string value to object property name [duplicate]

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?

Answers:

Answer

Use ['propname']:

objPosition[txtCol] = "whatever";

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

Answer

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

Answer

you can also set the object's key like this

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

Use the bracket notation like this:

objPosition["title"] = "Whatever";

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.