Skip to content

Instantly share code, notes, and snippets.

@ortense
Last active March 31, 2018 14:28
Show Gist options
  • Save ortense/0bd5f97a2d19a2de17fb5c0d1a292ae7 to your computer and use it in GitHub Desktop.
Save ortense/0bd5f97a2d19a2de17fb5c0d1a292ae7 to your computer and use it in GitHub Desktop.
A simple way to retrieve a property value from an object if it exist.
const get = (obj, prop, ...props) => {
const val = obj[prop]
if (!props.length || !val) return val
return get(val, ...props)
}
const propertyPathToArray = (path = '') =>
path.replace(/\[/g, '.').replace(/\]/g, '').split('.')
const prop = (path, obj) =>
get(obj, ...propertyPathToArray(path))
/*
const cat = {
name: 'Hiei',
color: 'Black',
address: { number: 2223 },
siblings: [
{ name: 'Minato', color: 'Yellow' }
]
}
prop('siblings[0].name', cat) // Minato
prop('address.number', cat) // 2223
prop('siblings[0].address.number', cat) // undefined
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment