Created
October 12, 2013 07:23
-
-
Save danscan/6946949 to your computer and use it in GitHub Desktop.
I was looking for a short, simple way to set and get deep properties in a single line in javascript, and after not finding anything I decided to see how short I could make these methods. Enjoy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Set deep property | |
| function setProperty(p,v){p=p.split('.'),i=0,w=("string"===typeof v?'"'+v+'"':v);while(p[i])eval(p.slice(0,++i).join('.')+'='+(p[i]?"{}":w));return v} | |
| // Example | |
| setProperty('some.really.deep.property', 'now exists'); // "now exists" | |
| // Get deep property | |
| function getProperty(p){p=p.split('.'),v=this;while(p[0]&&v){v=v[p.shift()]}return v} | |
| // Example | |
| getProperty('some.really.deep.property'); // "now exists" |
Author
You've inspired me: https://gist.github.com/lukeburns/6954291
You both inspired me: https://gist.github.com/kr1zmo/6958301
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So today, I wrote a one-line deep property setter/getter.
Here is the readable version.