1

I'm having a bit of trouble figuring something out. I need to use a ternary operator to return either a value or false but it's getting the data it needs from an object containing other nested objects and I can not be sure that either of those nested objects exist.

Data structure is as follows:

data = {
    "foo":{
        "bar": true,
        "tar": true,
        "rar": false
    },
    "goo":{
        "har": true,
        "par": true,
        "mar": false
    },
}

The ternary operator needs to basically do something like the following:

var something = data.foo.bar ? data.foo.bar : false

But it's possible that data.foo doesn't exist and also possible that data.foo.bar doesn't exist.

How can I make a check on either element not existing and returning false if either doesn't exist and returning the actual value if it does?

I don't believe this is a duplicate of the one it was marked as a duplicate of as I specifically need it to be a ternary operator. Ifs are not suitable to my purpose.

Steve
  • 576
  • 2
  • 7
  • 21
  • 2
    Your code is syntactically invalid. You can't use numbers as property names that way; you have to use the `[ ]` operator instead of `.`. – Pointy Aug 02 '17 at 22:32
  • Yeah I'm aware of this, I was just using dummy data. I'll make it correct. Thanks! – Steve Aug 02 '17 at 22:33
  • Also, ternary operators, while efficient, can make for difficult to read code, especially when the condition is complex to read, that being said, a ternary operator is simply an if statement, so just check if it is `undefined` as well. – Leeish Aug 02 '17 at 22:34
  • I mean. You could extend your ternary to check if the object exists to begin with, but you should probably just use an if statement for clarity. – zfrisch Aug 02 '17 at 22:34

1 Answers1

1

You can use the in operator:

var x = (1234 in data && data[1234] && 5678 in data[1234]) ?
    data[1234][5678] :
    false;

Structures like that are error-prone, which is probably obvious from the very existence of the question.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Hey thanks for this, yeah this worked. Unfortunately I have to use ternary (I'm using it as an option for selecting a CSS class in Vue.js based on a computed property if that means anything to you and as far as I'm aware the only way this can be accomplished is using a ternary.) – Steve Aug 02 '17 at 22:45
  • And as it turns out this makes my code really slow :/ Ah well, thanks for the answer! – Steve Aug 02 '17 at 22:49