Reputation: 36937
I'm trying to sort out if this is plausible but have gotten syntax errors at best. So I am wondering if it is at all possible.
What I have is an object (example only)
var myObj = {
something1_max:50,
something1_enabled:false,
something1_locked:true,
something2_max:100,
something2_enabled:false,
something2_locked:true,
something3_max:10,
something3_enabled:true,
something3_locked:true
}
and what I want to do through a function is do something like again for example to sum things up..
function displayDetails(theScope, obj)
{
console.log(obj.[theScope]_max);
}
(function(){displayDetails('something3', myObj);})()
so when displayDetails()
is called whatever the scope I can see in this example the max for that scope. In the console log for the example I would hope to see 10
Upvotes: 0
Views: 46
Reputation: 91608
Properties of JavaScript objects can always be accessed as a string using the bracket syntax, ie object['property']
. This, of course, means you can build that string dynamically:
console.log(obj[theScope + '_max']);
Upvotes: 1
Reputation: 24352
Put the property name string in brackets.
console.log(obj[theScope + '_max']);
Upvotes: 1