Sign in
Log inSign up

Post hidden from Hashnode

Posts can be hidden from Hashnode network for various reasons. Contact the moderators for more details.

Recurring object properties - JS

Cristian Gherghel's photo
Cristian Gherghel
·Oct 14, 2020·

1 min read

If you ever get into trouble (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 a dot.

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