Space Ostrich
Space Ostrich

Reputation: 423

For in getting object property identifier instead of property value?

I'm trying to display the values of an array of student objects in a table. Using the following code to create and assign text to the cells of the table:

var tableBody = document.createElement('tableBody');
                table.appendChild(tableBody);
                body.appendChild(table);
                students.forEach(function(student) {
                    var row = document.createElement('tr');
                    for(var property in student) {
                        var cell = document.createElement('td');
                        cell.textContent = property.toString();
                        row.appendChild(cell);
                    };
                    tableBody.appendChild(row);
                });

When I run the program I get a table like I want, but instead of a list of students and scores I get a table with the property identifier. The correct number of columns and rows all displaying the word name and score.

I tried adding different variations of:

property.value.toString();

but they've all resulted in an "is undefined" error. I can't find anything on the subject online, with the closest thing I've found using a forEach loop to get the properties, which isn't even possible. Is there some form of syntax I'm not aware of that I need to add in order to read the actual value of each property? Or will I need to use a different kind of loop completely?

Upvotes: 0

Views: 176

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

You need to show the property value and not just the property right.

replace

cell.textContent = property.toString();

with

cell.textContent = student[property].toString();

or simply

cell.textContent = student[property];

Upvotes: 1

Related Questions