Last active
August 29, 2015 14:16
-
-
Save loicknuchel/e4a21fad01e9e689f1c7 to your computer and use it in GitHub Desktop.
do: magic({"a": {"b": {"c": "hey"}}}, "a.b.c") === "hey"
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
// 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 |
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 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