1

My Problem

Consider a comparison on a nested property of an object:

display.entities.listAfter.text === 'blah';

If one of the properties in the nested lookup does not exist, we would get a type error, for example:

TypeError: Cannot read property 'listAfter' of undefined

What have I tried

Try and catch. Works, but not very elegant and I wonder if there's a better way.

My Wuestion

Is there a canonical way - besides try and catch - to check whether a nested property exists before making a comparison?

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • Possible duplicate of [Test for existence of nested JavaScript object key](https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key) – Félix Paradis Sep 13 '18 at 19:20

2 Answers2

1

I don't know about canonical, but I'll do this sometimes:

display.entities &&
display.entities.listAfter &&
display.entities.listAfter.text === 'blah'

But of course that gets unwieldy pretty fast. If you really want it to look nice, turn to lodash!

https://lodash.com/docs/4.17.10#get

You can provide a path to the .get function, and even specify a default if it's not found

_.get(display, 'entities.listAfter.text') === 'blah'
Steve Archer
  • 641
  • 4
  • 10
0

I love using a simple functional getter for nested properties with smart defaults as:

const getValue = (obj = {}, path = []) => {
  return path.reduce((xs, x) => (xs && xs[x]) ? xs[x] : undefined, obj);
};

const display = {
  "entities": {
    "listAfter": {
      "text": 1
    }
  }
};
console.log(getValue(display, ['entities', 'listAfter', 'text']));
console.log(getValue(display, ['entities', 'listAfter', 'foo']));
console.log(getValue(display, ['entities', 'listAfter']));
vorillaz
  • 6,098
  • 2
  • 30
  • 46