2

I only found solutions for variables, that were undefined, not the use case that I have at the moment.

I am building an object, from another object, where I am assigning a number of values from the input object, e.g.

valueQuantity: {
      value: observation['obx.5'][0]['obx.5.1'][0],
      unit: observation['obx.6'][0]['obx.6.1'][0]
},

In some input object the values are defined in some they aren't. In that case I want value and unit to be null, however this errors out obviously.

(node:36779) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined

In this case observation['obx.5'][0] was already undefined.

I could do a try/catch, but as the resulting object is pretty long, this would become extremely unreadable.

Any way to do this gracefully?

rStorms
  • 1,036
  • 2
  • 11
  • 23
  • Does this answer your question? [In javascript how can I dynamically get a nested property of an object](https://stackoverflow.com/questions/6906108/in-javascript-how-can-i-dynamically-get-a-nested-property-of-an-object) – Hector Ricardo Jan 21 '20 at 07:07
  • 1
    Sounds like you want [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) which is a very new addition to JS (so browser support is very limited). You can find a more browser compatible version [here](https://stackoverflow.com/questions/14782232/how-to-avoid-cannot-read-property-of-undefined-errors/42349521#42349521). – Nick Parsons Jan 21 '20 at 07:12
  • Yes, optional chaining sounds perfect! – rStorms Jan 21 '20 at 07:16

1 Answers1

0

You can use lodash's get function to retrieve nested properties from an object.

From the docs:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// => 3

_.get(object, ['a', '0', 'b', 'c']);
// => 3

_.get(object, 'a.b.c', 'default');
// => 'default'
Hector Ricardo
  • 497
  • 5
  • 16
  • Looked for this, thanks. Can I do this somehow using Javascripts Object destructuring? I am not sure, as I have to traverse through object and arrays... – rStorms Jan 21 '20 at 07:11
  • No, you use object destructuring for assignments of a top-level property to a variable....in this case, because you want to retrieve nested properties, that won't help – Hector Ricardo Jan 21 '20 at 07:16
  • optional chaining sounds like the perfect answer, but as of now, lodash seems to do the trick. Thanks. – rStorms Jan 21 '20 at 07:19