Home > Enterprise >  cannot access object property by iterating array
cannot access object property by iterating array

Time:06-03

In this excercise I created 3 functions :

score() to generate a random Number.

generateStudents to create a list Object. object has format {student:'name',marks:{...}} as define in generateStudents().

However, When I tried to access student name (in the last function) by 1. create a variable obj and assign it to generateStudents() and 2. access each element by a for loop and access property name as obj[i].name. however it return an error Cannot read properties of undefined (reading 'name'). Can someone help ?

var score = function getRandomMark(start, end, step) {

    var num = start
    var arr = []
    arr.push(num)
    while (num <= (end - step)) {
        num  = step
        arr.push(num)
    }
    var index = Math.floor(Math.random() * (arr.length))


    return (arr[index])
}
var generateStudents = function generateStudent(nameArr) {
    var studentArr = []
    for (let i = 0; i < nameArr.length; i  ) {
        var student = {
            "name": nameArr[i],
            "marks": {
                "literature": score(6, 10
                    , 0.5),
                "maths": score(6, 10
                    , 0.5),
                "chemistry": score(6, 10
                    , 0.5),
                "history": score(6, 10
                    , 0.5),
                "biology": score(6, 10
                    , 0.5)
            }
        }
        studentArr.push(student)

    }
    return studentArr
}
var markList = ["Chi", "Duc", "Huy"]

var findStudentMinMax = function findStudentMinMax() {

    var obj = generateStudents(markList)
    console.log(typeof (obj))

    var obj1 = {}
    var obj2 = {}

    var arr1 = []
    var arr2 = []

    const keys1 = Object.keys(obj[0]["marks"])

    for (let i = 0; i < keys1.length; i  ) {

        var name = obj[i].name
        console.log(obj[i])
    }
}
findStudentMinMax()

CodePudding user response:

obj[i] is the result of score(6, 10, 0.5), if you want to get the name you should get it from the object: obj[0].name Take care that you are not iterating the students, just getting the first one.

Highly recommended: Use descriptive names for your variables. obj, obj1, obj2, arr1, arr2, keys1, etc... do not tell anything about what they are and that provokes difficulties to understand the code.

CodePudding user response:

The problem is the following: Object.keys(obj[0]["marks"]) are the keys of the score object. This array has 5 entires. However, in the for-loop you use the index to access the i-th element of obj which is an array of three entires only. This is the reason the first three entries get logged to the console before the script crashes as there is no fourth element in obj.

You might wanted to do something like this:

for (let i = 0; i < obj.length; i  ) {
    var name = obj[i].name
    console.log(obj[i])
}

I can just repeat what A. Llorente already said as I think you messed up with the variable names:

Highly recommended: Use descriptive names for your variables. obj, obj1, obj2, arr1, arr2, keys1, etc... do not tell anything about what they are and that provokes difficulties to understand the code.

  • Related