Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

62
Vistas
cannot access object property by iterating array

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()

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda