Home > OS >  Javascript - Access nested elements of JSON object
Javascript - Access nested elements of JSON object

Time:10-03

So I have a series of 4 JSON objects with nested data inside each of them. Each of these objects are stored in an array called classes. Here is an example of how one of the class objects is formatted:

let class_A = {
    professor: "Joey Smith",
    numberStudents: 25,
    courseCode: "COMS 2360",
    seating: {
        "FirstRow": {
            0: {
                firstName: "Sarah",
                collegeMajor: "English",
            },
            1: {
                firstName: "Bob",
                collegeMajor: "Computer Engineering",
            },
            2: { 
                firstName: "Dylan",
                collegeMajor: "Mathematics",
            }
        },
        "SecondRow": {
            3: {
                firstName: "Molly",
                collegeMajor: "Music"
            }
        }
    }
};

I'm struggling to figure out how to access the very last fields within each class object (firstName and collegeMajor). The furthest I was able to get was the indexes beneath each row number.

let classes = [class_A, class_B, class_C, class_D];
let classesAvailable = document.getElementById('classes');
let class = classes[classesAvailable.value];

for(rowNum in class.seating){
    for(index in class.seating[rowNum]){
        console.log(index);
        //console.log(class.seating[rowNum[index]].firstName);
                
    }
}

So in this example, console.log(index) prints out:

0

1

2

3

but I'm unable to print the first name and college major of each student in each row. I was trying to follow a similar logic and do console.log(class.seating[rowNum[index]].firstName) but I get the error:

Cannot read properties of undefined (reading 'firstName')

Was wondering if anyone knows what's wrong with my logic here?

CodePudding user response:

console.log(class.seating[rowNum][index])
  • Related