Skip to content

Instantly share code, notes, and snippets.

@arnemart
Forked from 140bytes/LICENSE.txt
Last active March 8, 2018 11:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnemart/7135795 to your computer and use it in GitHub Desktop.
Save arnemart/7135795 to your computer and use it in GitHub Desktop.
Safely access nested object or array properties in 127 bytes
function(obj) {
// First argument is the object to search
// The rest of the arguments are the property names to search for
var args = Array.prototype.slice.call(arguments,1);
// Reduce over all the property names, descending further and further into the search object
// Seed value is the object we're searching
return args.reduce(function(obj, arg) {
// If the current object has the specified value, return it
if (obj !== undefined && obj.hasOwnProperty(arg)) {
return obj[arg];
// Otherwise return undefined
} else {
return undefined;
}
}, obj);
}
function(o){return[].slice.call(arguments,1).reduce(function(o,a){return o!==undefined&&o.hasOwnProperty(a)?o[a]:undefined},o)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
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 FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "safePropertyAccess",
"description": "Safely access properties of a deeply nested object.",
"keywords": [
"object",
"array",
"traverse"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>hello</b></div>
<div>Actual value: <b id="ret1"></b></div>
<div>Expected value: <b>undefined</b></div>
<div>Actual value: <b id="ret2"></b></div>
<div>Expected value: <b>9</b></div>
<div>Actual value: <b id="ret3"></b></div>
<div>Expected value: <b>false</b></div>
<div>Actual value: <b id="ret4"></b></div>
<script>
var getVal = function(o){return[].slice.call(arguments,1).reduce(function(o,a){return o!==undefined&&o.hasOwnProperty(a)?o[a]:undefined},o)}
var o = {
aa: {
bb: {
cc: 'hello',
dd: [8, 9, 10]
},
ee: false
}
};
document.getElementById('ret1').innerHTML = getVal(o, 'aa', 'bb', 'cc');
document.getElementById('ret2').innerHTML = getVal(o, 'aa', 'bb', 'kk');
document.getElementById('ret3').innerHTML = getVal(o, 'aa', 'bb', 'dd', 1);
document.getElementById('ret4').innerHTML = getVal(o, 'aa', 'ee');
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment