Last active
March 31, 2018 14:28
-
-
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.
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
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