ortense
3/31/2018 - 1:57 PM

javascript get property value

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
*/