Skip to content

Instantly share code, notes, and snippets.

@alanszlosek
Created January 6, 2014 22:16
Show Gist options
  • Save alanszlosek/8290784 to your computer and use it in GitHub Desktop.
Save alanszlosek/8290784 to your computer and use it in GitHub Desktop.
<html>
<head>
<script>
/*
Descends into an array or JSON object, looking for the specified elements
If one is not found, the fallback value (first argument) will be returned
Trying to alleviate the mix of error checking and object access that can litter code
*/
Object.prototype.dive = function() {
var source = this;
var fallback = arguments[0];
console.log('diving into:');
console.log(source);
for (var i = 1; i < arguments.length; i++) {
var element = arguments[i];
console.log('considering: ' + element);
if (typeof(element) == "string") {
if (source.hasOwnProperty(element)) {
source = source[element];
} else {
return fallback;
}
} else { // assume numeric
if (source.length >= element) {
source = source[ element ];
} else {
return fallback;
}
}
}
return source;
};
function test() {
var data = {
'response': {
'content': {
'errors': [
'one', 'two'
]
}
}
};
console.log( data.dive({}, 'response', 'content', 'errors', 1));
}
</script>
</head>
<body>
<button onclick="test();">Click me</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment