I have a custom object with a bunch of array properties.
function Location (name, displayName){
this.name = name,
this.displayName = displayName,
Location.objects.push(this);
}
Location.objects = [];
//Initialize Farm
var farm = new Location();
farm.scenes = [
"content 0",
"content 1",
"Content 2"
];
Using JQuery, I am grabbing an attribute from the DOM that I need to use to call values from within the object.
$('button').click(function(){
var location = $(this).attr('id'); //in this case, the id is 'farm'
mainLoop(location);
});
function mainLoop(location){
console.log(farm.scenes.length);// returns '3' as desired
console.log(location.scenes.length);//returns undefined because location is a string. I need this to work.
console.log(location[scenes][length]); //same problem
}
The only solution I've found this far is to use eval(), but I cannot do that because this data could be manipulated by the end user.
function mainLoop(location){
location = eval(location);
console.log(location.scenes.length);//returns 3 as desired
}
I need an alternative way to somehow take this string and turn it into an object property reference. In this case, I am working with a limited amount of results, so I could potentially map a set of strings to identifiers, but I feel like there's probably a more elegant solution for this, though I can't figure out what question I should be typing into stackoverflow.
There is a similar question Dynamically access object property using variable, but this doesn't apply here - both of the following lines using both forms of notation would have resolved '3'. I think my syntax is correct on the notation, so I must be doing something else incorrectly.
console.log(location.scenes.length); //returns undefined because location is a string. I need this to work.
console.log(location[scenes][length]); //same problem