Created
November 26, 2019 11:07
-
-
Save eldoy/b823f3c3470aa0e8cee01235606d911c to your computer and use it in GitHub Desktop.
Get an object value from path and return undefined if not found
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
// Get an object value from path | |
function getValue(obj, path) { | |
var keys = path.split('.') | |
for (var i = 0; i < keys.length; i++) { | |
try { | |
obj = obj[keys[i]] | |
} catch(e) { | |
return | |
} | |
} | |
return obj | |
} | |
const obj = { a: 1, b: { c: 2 } } | |
let value = getValue(obj, 'a') | |
console.log(value) // 1 | |
value = getValue(obj, 'b.c') | |
console.log(value) // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Without try catch: