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
  • 10

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 hatfield
  • 21,681
  • 4
  • 26
  • 25