Skip to content

Instantly share code, notes, and snippets.

@peteygao
Created January 8, 2014 21:17
Show Gist options
  • Save peteygao/8324835 to your computer and use it in GitHub Desktop.
Save peteygao/8324835 to your computer and use it in GitHub Desktop.
Is it possible to evaluating object/array accessors in JavaScript without using eval()?
/*
Scenario: App requests the user to provide accessors to an JSON object that they also provide.
e.g. User provides the following JSON object:
{ people: [
{ firstName: "Bob", lastName: "Jones" },
{ firstName: "Jane", lastName: "Jones" }
], numbers: [1, 2, 3]
}
The JSON object is saved to the 'data' variable by the app.
Then we request that the user specify what element they want to access and ask for a string input.
e.g. The user types '.people[0].firstName', expecting the output to be 'Bob'
We then save the user input into the 'userInput' variable as a string.
*/
eval('data' + userInput); // This will obviously work, but is it possible without using eval()?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment