简体   繁体   中英

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. Something like this:

function myFunc(e, myProperty) {

    alert( e.data[myProperty] );
}

var myValue = myFunc(myObject, "someField");

I get the value undefined .

I think the equivalent in ColdFusion would be something[myPropertyName] and I'm wondering if there is something similar in 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.

var myValue = e.data[myProperty];

var myData = { myProperty: myValue }

In the code above myProperty is being passed as "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

worked for me:

function myFunc(e, myProperty) {
    alert( e.data[myProperty] );
}

myObject = { data: {} };
myObject.data['someField'] = 123;
var myValue = myFunc(myObject, "someField");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM