Dynamically Forming a JSON object traversion without using eval
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
开发者_如何学Go
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.
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.
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
.
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.
精彩评论