[英]How do I dynamically get the value of a property of a JavaScript object?
I might not know what to call this, but essentially I want to pass the name of the property dynamically and then get the value of that property within my objects data property. 我可能不知道该怎么称呼,但是本质上我想动态传递属性的名称,然后在我的objects数据属性中获取该属性的值。 Something like this: 像这样:
function myFunc(e, myProperty) {
alert( e.data[myProperty] );
}
var myValue = myFunc(myObject, "someField");
I get the value undefined . 我得到的值是undefined 。
I think the equivalent in ColdFusion would be something[myPropertyName] and I'm wondering if there is something similar in JavaScript. 我认为ColdFusion中的等效项应该是[myPropertyName],我想知道JavaScript中是否存在类似的内容。
UPDATE: Apparently getting the value works, but not where I'm trying to pass the dynamic property as a name/value pair to an AJAX request. 更新:显然,获取值是可行的,但是在我试图将动态属性作为名称/值对传递给AJAX请求的地方,却不可行。
var myValue = e.data[myProperty];
var myData = { myProperty: myValue }
In the code above myProperty is being passed as "myProperty" 在上面的代码中, myProperty作为“ myProperty”传递
Please try: 请试试:
var myValue = e.data[myProperty];
var myData = { };
myData[myProperty] = myValue;
That should allow you to dynamically create an object with property named myProperty
那应该允许您动态创建一个具有名为myProperty
属性的对象
worked for me: 为我工作:
function myFunc(e, myProperty) {
alert( e.data[myProperty] );
}
myObject = { data: {} };
myObject.data['someField'] = 123;
var myValue = myFunc(myObject, "someField");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.