0

Consider a const that holds an object with multiple levels like this:

const test = {
  One: {
    a: 220,
    b: ['Chipotle', 'Subway', 'Habit Burger'],
  },
  Two: {
    a: 110,
    b: ['Chipotle'],
  },
  Three: {
    a: 200,
    b: ['Subway', 'Jack In The Box'],
  },
  Four: {
    a: 460,
    b: ['Chipotle', 'Subway', 'Habit Burger', 'Jack In The Box'],
  },
};

I know that, for example, if I want to access the first object's a value, I can say test.One.a, but how do I programmatically access the value of test.One, test.Two, etc. without hardcoding it?

Mario Parra
  • 1,504
  • 3
  • 21
  • 46

1 Answers1

1

Use the bracket notation for accessing properties:

test["One"]["a"];
test["Two"]["b"];

These work with strings, so you can use variables:

const test = {
  One: {
    a: 220,
    b: ['Chipotle', 'Subway', 'Habit Burger'],
  },
  Two: {
    a: 110,
    b: ['Chipotle'],
  },
  Three: {
    a: 200,
    b: ['Subway', 'Jack In The Box'],
  },
  Four: {
    a: 460,
    b: ['Chipotle', 'Subway', 'Habit Burger', 'Jack In The Box'],
  },
};

const first = Object.keys(test)[Math.floor(Math.random() * 4)];
const second = ["a", "b"][Math.floor(Math.random() * 2)];

console.log(first, second, test[first][second])
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34