Skip to content

Instantly share code, notes, and snippets.

@aaronmccall
Forked from 140bytes/LICENSE.txt
Last active December 18, 2015 01:09
Show Gist options
  • Save aaronmccall/5701675 to your computer and use it in GitHub Desktop.
Save aaronmccall/5701675 to your computer and use it in GitHub Desktop.
recursaprop: Eliminates the need to do data && data.prop && data.prop.subprop testing when accessing properties of objects. Given a dot-notated property (foo.bar.baz) of an object, returns the property or undefined if it or any step in the path does not exist.
// Eliminates the need to do data && data.prop && data.prop.subprop testing
// when accessing properties of objects.
function recursaprop(
s, // property string in dot notation e.g. foo.bar.baz
d, // data object
p, // placeholder for prop list
l, // placeholder for prop list length
i, // placeholder of iteration index
r, // placeholder for result
u // placeholder for undefined
) {
r = d;
p = s.split('.'); // populate prop list from property string
l = p.length; // get length
for (i=0; i<l; i++) {
r = r[p[i]]; // set result to be result's child property from prop list
if (r === u) return r; // if we didn't find anything, return early
}
return r;
}
function recursaprop(a,b,c,d,e,f,g){for(f=b,c=a.split("."),d=c.length,e=0;d>e;e++)if(f=f[c[e]],f===g)return f;return f}
DO WHAT THE HECK YOU WANT TO PUBLIC LICENSE
Version 1, December 2013
Copyright (C) 2013 Aaron McCall <https://github.com/aaronmccall>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE HECK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE HECK YOU WANT TO.
{
"name": "recursaprop",
"description": "Given a dot-notated property (foo.bar.baz) of an object, returns the property or undefined if it or any step in the path does not exist.",
"keywords": [
"object",
"properties",
"recursive"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>biz</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
function recursaprop(a,b,c,d,e,f,g){for(f=b,c=a.split("."),d=c.length,e=0;d>e;e++)if(f=f[c[e]],f===g)return f;return f}
var obj = {
foo: {
bar: {
baz: 'biz'
}
}
};
document.getElementById( "ret" ).innerHTML = recursaprop('foo.bar.baz', obj);
</script>
@atk
Copy link

atk commented Jun 4, 2013

Smaller variant (70 bytes) using regexp:

function r(a,b){a.replace(/[^.]+/g,function(c){b&&(b=b[c])});return b}

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