Recurring object properties - JS

If you ever get into troubles (and I'm sure you did) when trying to access a property of a JS object which does not exist twice, you will definitely get the red alert in the console.

Example:

const obj = {};

console.log(obj.foo.bar);

In order to fix that and get the property if exists or undefined if does not, we can create a very simple helper function like this:

function objProps (obj, props) {
  const response = props.split('.').reduce((acc, curr) => obj = obj[curr] ? obj[curr] : {}, obj)

  return JSON.stringify(response) === '{}' ? undefined : response
}

And to use it, just

console.log(objProps(obj, 'foo.bar');

So every time you wanna check if the props exist on the obj, just put them as a second argument in a String separated by dot.

PS: as always, thanks for reading && stay green!