JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2

Akeia Escobar
Akeia Escobar
1,800 Points

I got stuck trying to access the value

When I run this code it prints "undefined" at the top. Then name, track, etc., but the values of the object also print undefined. What am I doing wrong?

var HTML;

let students = [
  {
   name: 'Cayden',
   track: 'C#',
   achievements: 10,
   points: '2123'
  },

  {
   name: 'Akeia',
   track: 'Full Stack Development',
   achievements: 15,
   points: '4253'
  },

  {
   name: 'Yaya',
   track: 'Front End Development',
   achievements: 13,
   points: '2435'
  },

  {
   name: 'Jason',
   track: 'Beginner Python',
   achievements: 12,
   points: '2321'
  },

  {
   name: 'Ashley',
   track: 'iOS',
   achievements: '9',
   points: '1324'
  },
];

// print function

function print(message) {
  let outputDiv = document.getElementById('output');
  outputDiv.innerHTML = message;
}

//for loop to access array

for (i = 0; i < 4; i += 1 ) {
  for (studentData in students[i]) {
  HTML += '<p>' +  studentData + ': ' + studentData[students] + '</br>'
  }
}  

print(HTML);

2 Answers

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 50,935 Points

1) Initialize HTML with an empty string. Without a value you have the first undefined.

var HTML = "";

2) Access properties for the current array object students[i]

  HTML += '<p>' +  studentData + ': ' + students[i][studentData] + '</br>'

3) Use students.length (which equals 5 not 4) here:

for (i = 0; i < students.length; i += 1 ) {
Akeia Escobar
Akeia Escobar
1,800 Points

Thanks! That worked. Can you explain why students[i][studentData] works?

It's not really clicking

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 50,935 Points

From MDN on bracket notation:

Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it.

It then goes on to give an example of accessing properties of a car object but the syntax is basically:

object['property']

For the code students[i] is the object and studentData is the property

The first example here is similar

Loop through the properties of an object:

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
  text += person[x] + " ";
}
Akeia Escobar
Akeia Escobar
1,800 Points

Thanks. That helps a lot!