0
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

palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • Use computed property when you want to access property by a variable, i.e. `object[variable]` – Code Maniac Mar 21 '20 at 16:51
  • @CodeManiac I tried I also tried console.log('classtext: ' + classes[subject[classtitle]]) and that just outputs undefined for some reason. – Luciano Lim Mar 21 '20 at 16:52
  • can you post the complete class object. – Code Maniac Mar 21 '20 at 16:55
  • 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' }, }; Currently this is my entire class. – Luciano Lim Mar 21 '20 at 16:55
  • 1
    You need to use `classes[subject][classtitle]` – Code Maniac Mar 21 '20 at 16:57

1 Answers1

1

You can get the classtext using:

console.log('classtext: ' + classes[subject][classtitle])
palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • Thank you so much. I was trying to figure that out for so long. I kept putting the brackets in the brackets. It makes a lot more sense now. – Luciano Lim Mar 21 '20 at 16:56