Created
February 7, 2016 22:03
-
-
Save gmmorris/0bb6e36730ac3de521d4 to your computer and use it in GitHub Desktop.
Example of safe access using a string for the Safe Access Proxy article
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
const DarthVader = { | |
name : 'Anakin', | |
mother : { | |
name : 'Shmi' | |
} | |
}; | |
function deepAccessUsingString(obj, key){ | |
return key.split('.').reduce((nestedObject, key) => { | |
if(nestedObject && key in nestedObject) { | |
return nestedObject[key]; | |
} | |
return undefined; | |
}, obj); | |
} | |
let mothersName = deepAccessUsingString(DarthVader, 'mother.name'); | |
let fathersName = deepAccessUsingString(DarthVader, 'father.name'); | |
console.log(mothersName); // prints "Shmi" | |
console.log(fathersName); // prints undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment