1

I have a problem where I have data (returned from an API so I have no control over it) and I want to retrieve a value that is deeply nested within the data, but might not exist. For example, if the data looks like this:

const data = { level1: { level2: { level3: { level4: "value" } } } };

To get the value when I don't know if it exists I have to do:

const value =
  level1 && level1.level2 && level1.level2.level3 && level1.level2.level3.level4
    ? level1.level2.level3.level4.value
    : "missing";

Which becomes unwieldy and very hard to read when you have more levels and longer key names.
Is there a better way I can check whether a deeply nested value exists? vanilla JS please.

Max888
  • 3,089
  • 24
  • 55

0 Answers0