Search code examples
javascriptobjectjavascript-objects

Using variables to get Javascript Object properties?


var classes = {
    English: {
        requirement: 40,
        Eng9: 'English 9',
        Eng9H: 'English 9 Honors',
        Eng10: 'English 10',
        Eng10H: 'English 10 Honors',
        Eng11: 'English 11',
        APLang: 'AP Language',
        Eng12: 'English 12',
        Eng12H: 'AP Literature'
    },
};

for (var subject in classes) {
  console.log('processing subject: ' + subject)
  for (var classtitle in classes[subject]) {
    console.log('processing class: ' +classtitle);
    if (classtitle=='requirement') {
      continue;
    } else {
      console.log('subject: '+subject)
      console.log('classtitle: '+classtitle)
      console.log('classtext: ' + classes.subject.classtitle)
    }
  }
}  

console.log(classes.English.Eng9)

I'm starting to learn javascript and my first project is a sort of class sorting thing for my school. I can't figure out how to use variables when getting object properties in javascript. As an example, the console.log at the bottom properly outputs 'English 9', but the code above that keeps recognizing classes.subject as undefined. For reference I want the output to be something like

English 9
English 9 Honors
English 10

and so on

I also tried

console.log('classtext: ' + classes[subject[classtitle]])

and that just outputs classtext: undefined


Solution

  • You can get the classtext using:

    console.log('classtext: ' + classes[subject][classtitle])