0

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.