Search code examples
javascriptobjectundefined

Finds value of property


I am pretty new to Javascript. I am trying to get the sum of the grades of the 3 student properties i have declared. The problem is that i dont understand why it says undefined on my "grade" value. Also if there is any other easier way to find the values of the grades of each student other than writing it like:

classroom.student1.grade + classroom.student2.grade + classroom.student3.grade

Thank you in advance!

let classroom = {
numberOfChairs: 20,
numberofTables: 10,
student1: [
    {fullName: "", 
    age: "", 
    grade:8,
    electronics: {
        brand:"", 
        model:"",
        batteryCapacity:""
    }}
],
student2: [
    {fullName: "", 
    age: "", 
    grade:8,
    electronics: {
        brand:"", 
        model:"",
        batteryCapacity:""
    }}
],
student3:[
    {fullName: "", 
    age: "", 
    grade: 8,
    electronics: {
        brand:"", 
        model:"",
        batteryCapacity:""
    }}
],
teachers: [
    {fullName:"", yearsOfExperience:"", salary:""}
],
};

function getGrades() {
    grades = classroom.student1.grade + classroom.student2.grade + classroom.student3.grade 
        console.log(grades)
}

getGrades();

`

I am trying to find out why it says that my value of the students is "undefined" and what i shall write differently for it to find the value.


Solution

  • Because students are arrays each with one item, I don't think it's a good structure, If you ensure that you have only one item, you should refer the property directly to the object, then it will work fine.

    let classroom = {
    numberOfChairs: 20,
    numberofTables: 10,
    student1: {fullName: "", 
        age: "", 
        grade:8,
        electronics: {
            brand:"", 
            model:"",
            batteryCapacity:""
        }},
    student2:
        {fullName: "", 
        age: "", 
        grade:8,
        electronics: {
            brand:"", 
            model:"",
            batteryCapacity:""
        }},
    student3:
        {fullName: "", 
        age: "", 
        grade: 8,
        electronics: {
            brand:"", 
            model:"",
            batteryCapacity:""
        }},
    teachers: [
        {fullName:"", yearsOfExperience:"", salary:""}
    ],
    };
    

    Anyway, with this structure as the target object is first item in the array, you need to access the zero index.

    classroom.student1[0].grade + classroom.student2][0].grade + classroom.student3[0].grade