0

I am not a JS developer (using JS inside WKWebView on iOS, and it needs to inject some data onto a page, but that makes no difference for this question, as I'm interested in purely JS aspect of it), hence this is a very basic question, apologies for that.

I have a structure like this:

{ "a": 
  { "b": 
    { "c": 
      { "property": "value" }
    }
  }
}

Everything from "a" down to "property" is optional, and may not be present. I need to get the value of the "property".

Currently I have this:

  function f(value) {

      var json = JSON.parse(value);
      ...
      var prop = json.a.b.c.property;
      ...

This seems works, but of course if any part of a.b.c.property is missing I am getting an error in log:

A JavaScript exception occurred: TypeError: undefined is not an object (evaluating 'json.a.b.c.property')

Instead I want to exit function early if property is not present. So do I need to compare each level to undefined, or is there a better way to do it?

    var json = JSON.parse(value);
    if json.a == undefined || json.a.b == undefined || json.a.b.c == undefined || json.a.b.c.property == undefined {
        return;
    }
    ...
    var prop = json.a.b.c.property;
    ...
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
timbre timbre
  • 12,648
  • 10
  • 46
  • 77

1 Answers1

1

If you are using a modern web browser (read: not IE), then you can use the new ?. operator.

var prop = json?.a?.b?.c.property;
gen_Eric
  • 223,194
  • 41
  • 299
  • 337