0

I'm trying to create a simple table with jQuery by looping through an array of objects but get this message in the console:

TypeError: 'undefined' is not an object (evaluating 'people[i].lastName')

It works if I define the specific object (i.e. John.lastName) but not using the array[i], am I doing something wrong?

var person = function(firstName, lastName) {
    this.firstName = firstName || "Anonymous";
    this.lastName = lastName || "Anonymous";
    };

    var John = new person("John", "Walter");
    var Bob = new person("Bob", "Stevens");
    var Gerry = new person("Gerry", "Cricket");
    var Frank = new person("Frank", "Bloom");

    var people = [John, Bob, Gerry, Frank];

    for (i = 0; i < people.length; i++) {

    $(document).ready(function() {
    $("body").append("<table><tr><td>" + people[i].lastName + "</td></tr></table>");
    });

    };
2
  • 2
    The given code works. jsfiddle.net/qYb66 What are you not telling us? Also not sure why you have $(document).ready(function() { inside of the foreach loop. Commented Jun 1, 2014 at 16:24
  • 1
    You also create 4 tables instead of 1. Commented Jun 1, 2014 at 16:34

1 Answer 1

1
You can't put a $(document).ready within a for loop. Put your function inside the document.ready and your code works fine. To Add a table before the for loop and the /table 
after the for loop to prevent making each row in the array a table.

     $(document).ready(function()
  {
var person = function(firstName, lastName) {
    this.firstName = firstName || "Anonymous";
    this.lastName = lastName || "Anonymous";
    };

    var John = new person("John", "Walter");
    var Bob = new person("Bob", "Stevens");
    var Gerry = new person("Gerry", "Cricket");
    var Frank = new person("Frank", "Bloom");

    var people = [John, Bob, Gerry, Frank];
        $("body").append("<table>");

    for (i = 0; i < people.length; i++) {
console.log(people[i]);

   $("table").append("<tr><td>" + people[i].lastName + "</td></tr>");

    };
    $("<table>").append("</table>");
    });
Sign up to request clarification or add additional context in comments.

2 Comments

It's still creating 4 tables instead of one though
I updated the example to make only one table. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.