Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

61
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda