0

I am trying to create a program that defines the variable finalResult based on variable input. The input variable should call on an object inside of object A:

var input = "";
var A = {
   AA: {
      result: 0
   },
   AB: {
      result: 1
   }
}
var finalResult = A.input.result;

So if input = "AA", then the final result should be 0, but if input = "AB", then the final result should be 1.

Batchguy
  • 27
  • 12
  • 1
    `A[input].result` – ray Oct 03 '19 at 03:12
  • Hey, just use var finalResult = A[input][‘result’]; – James Dullat Oct 03 '19 at 03:12
  • 1
    You should read about [Javascript property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). Use bracket notation: in your case, `var finalResult = A[input].result` – Ian Oct 03 '19 at 03:15

1 Answers1

0

You can do A[input].result, which assumes the value of input is present as a property in A. If the property isn’t present you’ll get an error trying to access result on undefined. You can guard against this by OR’ing it with an empty object:

(A[input] || {}).result // undefined if A[input] isn’t present
ray
  • 26,557
  • 5
  • 28
  • 27