Why are these properties of my objects undefined during a for in loop?

68 views Asked by At

I am trying to figure out why this code won't log the actual property values, and instead just logs undefined over and over, even though I thought I created the property 'random' in each object and gave it a value with Math.random().

var students = [{id:'1'}, {id:'2'}, {id:'3'}, {id:'4'}];


sortStudents(resetRandom(students));

function resetRandom(ary) {
    for (var i = ary.length - 1; i >= 0; i--) {
        ary[i]['random'] = Math.floor(Math.random()*10000);
    };
    return ary
}

If I console.log() the students array after invoking resetRandom(students) the 'random' property is defined as a number like expected, in each of the objects in the array. The function below is where the problem occurs when I try to log that property I just get undefined:

function sortStudents(ary) {

    for (var i = ary.length - 1; i >= 0; i--) {
        for(var key in ary[i]) {
            if (key === 'random') {
                console.log(ary[key]);
            }

        }
    };

}
1

There are 1 answers

0
Royi Namir On BEST ANSWER

Change

 if (key === 'random') {
                console.log(ary[key]);
            }

to :

 if (key === 'random') {
                console.log(ary[i][key]);
            }