Skip to content

Instantly share code, notes, and snippets.

@loicknuchel
Last active August 29, 2015 14:16
Show Gist options
  • Save loicknuchel/e4a21fad01e9e689f1c7 to your computer and use it in GitHub Desktop.
Save loicknuchel/e4a21fad01e9e689f1c7 to your computer and use it in GitHub Desktop.
do: magic({"a": {"b": {"c": "hey"}}}, "a.b.c") === "hey"
// Quick & Unsafe way...
// + with eval your var MUST be global & you MUST know its name
var obj = {"a": {"b": {"c": "hey"}}};
var path = "a.b.c";
console.log(magic(obj, path)); // hey
console.log(eval("obj."+path)); // hey
console.log(obj.a.b.c); // hey
var wrongPath = "b.c";
console.log(magic(obj, wrongPath)); // undefined
console.log(eval("obj."+wrongPath)); // Error
console.log(obj.b.c); // Error
function magic(obj, path){
if(path === ''){
return obj;
} else if(Array.isArray(path)){
if(path.length > 0 && obj !== undefined){
var attr = path.shift();
return magic(obj[attr], path);
} else {
return obj;
}
} else {
return magic(obj, path.split('.'));
}
}
Object.prototype.getByPath = function(path){
return magic(this, path);
};
console.log('magic', magic({"a": {"b": {"c": "hey"}}}, "a.b.c")); // hey
console.log('getByPath', {"a": {"b": {"c": "hey"}}}.getByPath("a.b.c")); // hey
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment