Skip to content

Instantly share code, notes, and snippets.

@alexkhismatulin
Created May 13, 2019 16:35
Show Gist options
  • Save alexkhismatulin/0dee70114e597a32bcd59c6acc934d79 to your computer and use it in GitHub Desktop.
Save alexkhismatulin/0dee70114e597a32bcd59c6acc934d79 to your computer and use it in GitHub Desktop.
A simple errors-safe function allowing to access properties of objects/arrays by string key like
const getProperty = (obj, path, defaultValue) => {
const tokens = path.split(/[.[\]]+/g).filter(Boolean)
if (!obj || typeof obj !== "object") return defaultValue
if (tokens.length === 1) {
return (obj[tokens[0]] === undefined) ? defaultValue : obj[tokens[0]]
}
return getProperty(obj[tokens[0]], tokens.slice(1).join("."), defaultValue)
}
// example
const obj = { a: 3, b: [1, 2, 3], c: { d: 42 } }
console.log(getProperty(obj, "c.d")) // 42
console.log(getProperty(obj, "c.d.e")) // undefined
console.log(getProperty(obj, "c.d.e", "ooops")) // ooops
console.log(getProperty(obj, "b[0]")) // 1
console.log(getProperty(obj, "b.2")) // 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment