Skip to content

Instantly share code, notes, and snippets.

@danscan
Created October 12, 2013 07:23
Show Gist options
  • Select an option

  • Save danscan/6946949 to your computer and use it in GitHub Desktop.

Select an option

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.
// 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"
@danscan

danscan commented Oct 12, 2013

Copy link
Copy Markdown
Author

So today, I wrote a one-line deep property setter/getter.

function(p,v){p=p.split('.'),v=(v?(function(){i=0,w=("string"===typeof v?'"'+v+'"':v);while(p[i])eval(p.slice(0,++i).join('.')+'='+(p[i]?"{}":w));return v})():(function(){v=this;while(p[0]&&v)v=v[p.shift()];return v})());return v}

Here is the readable version.

function deepProperty(p,v){
    p=p.split('.'),
    v=(v?(function(){
        i=0,
        w=("string"===typeof v?'"'+v+'"':v);
        while(p[i])eval(p.slice(0,++i).join('.')+'='+(p[i]?"{}":w));
        return v
    })():(function(){
        v=this;
        while(p[0]&&v)
            v=v[p.shift()];
        return v
    })());
    return v
}

@lukeburns

Copy link
Copy Markdown

ghost commented Oct 13, 2013

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment