Skip to content

Instantly share code, notes, and snippets.

@postpostscript
Last active February 26, 2016 15:50
Show Gist options
  • Save postpostscript/7af2b022744f57402e94 to your computer and use it in GitHub Desktop.
Save postpostscript/7af2b022744f57402e94 to your computer and use it in GitHub Desktop.
Nested Object Protection Wrapper
var object = {
"value": 1,
"anotherValue": 2,
"nested": {
"value": 3
}
};
object.value
// => 1
var object2 = protectedWrapper(object);
object2.get('value')
// => 1
object2.get('nested.value')
// => 3
function protectedWrapper(object) {
return {
get: function(key) {
if (typeof key === 'undefined' || typeof key === 'null') {
return;
}
var obj = extend({}, object);
key.split(/[\[\]\.]/g).filter(Boolean).forEach(function(key) {
obj = obj ? obj[key] : null;
});
return typeof obj == 'object' ? protectedWrapper(obj) : obj;
}
}
}
function extend() {
var result = arguments[0];
for(var i = 1; i < arguments.length; i++) {
for(var key in arguments[i]) {
result[key] = arguments[i][key];
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment