Last active
February 26, 2016 15:50
-
-
Save postpostscript/7af2b022744f57402e94 to your computer and use it in GitHub Desktop.
Nested Object Protection Wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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