Skip to content

Instantly share code, notes, and snippets.

@eldoy
Created November 26, 2019 11:07
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 eldoy/b823f3c3470aa0e8cee01235606d911c to your computer and use it in GitHub Desktop.
Save eldoy/b823f3c3470aa0e8cee01235606d911c to your computer and use it in GitHub Desktop.
Get an object value from path and return undefined if not found
// 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
@eldoy
Copy link
Author

eldoy commented Dec 14, 2019

Without try catch:

function getValue(obj, path) {
  const keys = path.split('.')
  for (let i = 0; i < keys.length; i++) {
    if (!(obj = obj[keys[i]])) return
  }
  return obj
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment