I have an variable obj defined as follows:
{user: {username: "AzureDiamond", password: "hunter2"}}
I have a string str that might be defined as any of the following strings:
- “user”
- “user[username]”
- “user[password]”
- “fake”
Is there a relatively easy way for me in JS (specifically node.js) to essentially/dynamically perform the following?
- when
str == "user", return{username: "AzureDiamon", password: "hunter2"} - when
str == "user[username]", return “AzureDiamond” - when
str == "user[password]", return “hunter2” - when
str == "fake", returnnull
Edit: This question is more to find out if there’s anything easier or build into JS/node.js that I can use other than regex matches.
Solution
If you are sure the syntax of
stris correct, the function could look like this:Test
This is how it behaves:
Explanation
The script does not use regular expression, nor dangerous
eval()calls, only assumes your “path” will start with one word without brackets and every next part (if any) will be word enclosed in square brackets. If some path will not be found within the traversed object,nullwill be returned. If it will be found, it will be returned (regardless of whether it will be some complex object, string,null, boolean or anything else).Script begins with parsing your path. It does that by removing closing square brackets (“
]“) and splitting resulting string by opening square brackets (“[“). The process looks like this:So, as you see, at the end you have an array of path elements. These are evaluated one by one. If at any level appropriate step cannot be made deeper into the structure of the data argument, then
nullis returned. Otherwise the last accessed element is returned.Proof
Proof that it works is here: http://jsfiddle.net/EJCgE/2/
EDIT: There was some issue with more complex paths (when there were more than two levels), resulting from how string’s
replace()method works. I have updated my code to not include jQuery and to fix that issue.EDIT2: I have updated the script to remove redundant lines and one redundant variable.