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?
Use ['propname']
:
objPosition[txtCol] = "whatever";
Demo: http://jsfiddle.net/hr7XW/
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With