How can I access the properties inside my object with a for loop?

(I’m aware I might be able to use a for in loop, but I’d prefer to use a for loop for this)

Hey, I’m sorry if this is a dumb question, I’m still learning my way through JavaScript by challenging myself a bit more. I’ve spent all day with this issue but I can’t seem to figure it out and need some help.

I have the following JavaScript code for my object:

let student_information = {
    student1: { 
        name: "John",
        school: "School1"
    },
    student2: { 
        name: "Jane",
        school: "School2"
    }
};

I’m using the following for loop:

 for(let i = 0; i < Object.keys(student_information).length; i++) { 
           console.log(Object.keys(student_information)[i]);
        }

I know that this just simply outputs student1 and student2. But I want to access the nested objects inside each of the keys.

For instance, how would I grab the school name for student1 by running it through the loop?

I know I can do student_information.student1.school, but I need it to run through a loop and achieve it this way.

Is my approach wrong? How can I achieve my desired outcome?
I’d really appreciate if anyone could help me out!

student_information = {
    student1: { 
        name: "John",
        school: "School1"
    },
    student2: { 
        name: "Jane",
        school: "School2"
    }
};

keys = Object.keys(student_information)
values = Object.values(student_information)
entries = Object.entries(student_information)

for (let key of keys) console.log(key)
// "student1"
// "student2"
for (let value of values) console.log(value)
// { name: "John", school: "School1" }
// { name: "Jane", school: "School2" }
for  (let entry of entries) console.log(entry)
// ["student1", { name: "John", school: "School1" }]
// ["student2", { name: "John", school: "School1" }]

for (let i = 0; i < keys.length; i++) console.log(keys[i])
// "student1"
// "student2"
for (let i = 0; i < values.length; i++) console.log(values[i])
// { name: "John", school: "School1" }
// { name: "Jane", school: "School2" }
for (let i = 0; i < entries.length; i++) console.log(entries[i])
// ["student1", { name: "John", school: "School1" }]
// ["student2", { name: "John", school: "School1" }]

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.