views:

123

answers:

3

Given I have the following: (which is dynamically generated and varies in length)

associations = ["employer", "address"];

Trying to traverse the JSON object, and wanting to form something like the following:

data.employer.address

or

data[associations[0]][association[1]]

Without doing this:

eval("data."+associations.join('.'));

Finally, I may be shunned for saying this, but is it okay to use eval in an instance like this? Just retrieving data.

+1  A: 

Why not just iterate over your associations?

function traverse(data, associations){
  for (var i=0; i<associations.length; i++){
      data = data[associations[i]];
  }
  return data;
}

Your eval method has to generate a new string and parse the code before it can even start traversing.

z5h
This is perfect, thank you. Anything hinting at recursion usually fries my brain.
Matt Willhite
In fact, simple iteration will be much faster (in Javascript) than recursion or functional reduce/fold.
z5h
A: 

Here’s one way using Prototype.

$A(associations).inject(data, function (obj, method) {
  return obj[method];
});

Using eval is fine if you can guarantee the user won’t be able affect the string you’re passing to it. If your input is coming from the user or from a URL that could be changed by the user, you should probably avoid eval.

Todd Yandell
A: 

You can always create a dynamic script node. For instance:

var yo = document.createElement("script");
yo.setAttribute("type", "text/javascript");
yo.innerHTML = "alert('yo!');";
document.body.appendChild(yo);

No eval required.

Civil Disobedient