P5.js Object array of title names are not being recognized

Before adding the stars I’m trying to figure out why the titles are not appearing on the book objects. I’m sure it’s a simple oversight on my part, but if anyone can help it is sincerely appreciated!

var myBooks = [
{
    title: "The Giver",
    stars: 4
},
{   
    title: "Tess",
    stars: 5
},
{   
    title: "Great Gatsby",
    stars: 5
}
];

// draw shelf
fill(173, 117, 33);
rect(0, 120, width, 10);

var x = 10;

for (var i = 0; i < myBooks.length; i++){
    fill (214, 255, 219);
    noStroke();
    rect (x, 20, 90, 100);
    fill(0, 0, 0);
    text (myBooks.title, x, 30, 70, 100);
    //image(getImage("cute/Star"), 13 + i * 20, 90. 20, 30);

    x = x + 100;
}
1 Like

Your myBooks variable is an array.

What is myBooks.title? Is there an element in your array at index ‘title’? Nope!

myBooks[0], however, is the first book in the array. It has a title!

The fix is on the line that draws your text:

text (myBooks[i].title, x, 30, 70, 100);
2 Likes

Thank you @TfGuy44!! :grinning: My previous attempts to place the [i] were all wrong.

And now I want to show the stars. Each row of stars should appear within the book object near bottom edge. ***Please see comment line above code for stars placement for the area in question.

var myBooks = [
{
    title: "The Giver",
    stars: 4
},
{   
    title: "Tess",
    stars: 5
},
{   
    title: "Great Gatsby",
    stars: 5
}
];

// draw shelf
fill(173, 117, 33);
rect(0, 120, width, 10);

var x = 10;

for (var i = 0; i < myBooks.length; i++){
    fill (214, 255, 219);
    noStroke();
    rect (x, 20, 90, 100);
    fill(0, 0, 0);
    text (myBooks[i].title, x, 30, 70, 100);

//I'm not sure what the syntax here should be to show the stars
    image (myBooks[i].stars.getImage("cute/Star"),  13 + i * 20, 90. 20, 30); 

    x = x + 100;
}
//I'm not sure what the syntax here should be to show the stars image
(myBooks[i].stars.getImage("cute/Star"), 13 + i * 20, 90. 20, 30);

should be more like ( untested )

text (myBooks[i].title, 10, i * 30, 70, 100);
for (var k = 0; k < myBooks[i].stars ; k++){
  image( star, 13 + k * 20, 20+i * 30);
}
  • myBooks is a global variable which refers to an Array of 3 objects.
  • Each of those 3 objects got 2 properties: title & stars.
  • Property title is of datatype String.
  • While property stars is of datatype Number.
  • A JS Number doesn’t have any method named getImage().
1 Like