Skip to content

Instantly share code, notes, and snippets.

@gmmorris
Created February 7, 2016 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmmorris/0bb6e36730ac3de521d4 to your computer and use it in GitHub Desktop.
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
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