-2

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
Community
  • 1
  • 1
JPillow
  • 9
  • 1

1 Answers1

0

Since using location = eval(location); transforms it into the object you want, I assume that location as being passed in to your mainLoop function is simply the JSON string representing the object, equivalent to '{"scenes" : ["content 0", "content 1", "Content 2"]}'

What you can do is use JSON.parse - in this case:

console.log(location);
// outputs '{"scenes" : ["content 0", "content 1", "Content 2"]}'
location = JSON.parse(location);
console.log(location.scenes.length); // outputs 3

Nowadays, it's pretty much standard in browsers. There is more information on JSON.parse in this related SO question, which points out that if you're already using jquery (which it looks like you are), then you can use $.parseJSON which will handle older browsers by falling back to eval.

Community
  • 1
  • 1
Krease
  • 15,805
  • 8
  • 54
  • 86