Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Displaying result of array of objects to the webpage

I am trying to display objects from an array, when I click on the button all I am getting is part of the result displaying on the page. Here is the code below:

function getRandomQuote() {
  //select a random quote from the quotes array
  var random = Math.floor(Math.random() * quotes.length);
  for(var prop in quotes[random])
  {
     document.getElementById('quote-box').innerHTML = quotes[random][prop];
   }
 }

//create a function called printQuote
function printQuote(){
    var randomQuote = getRandomQuote();

    var quote = "<p class='quote'>"+ quote +"</p>";
        quote += "<p class='source'>"+ source + "</p>";
     document.getElementById('quote-box').innerHTML = quote;
     return randomQuote;
}

1 Answer

0yzh 󠀠
0yzh 󠀠
17,276 Points

You want your getRandomQuote function to just return the randomly selected object, and not iterate through it yet. You can then use your printQuote function to go through the object and build your html string with the object's properties like quote / source / citation, etc.

Example:

function getRandomQuote() {
  //select a random quote from the quotes array
  var random = Math.floor(Math.random() * quotes.length);
  // return the object
  return quotes[random];
 }

//create a function called printQuote   ***in here you will build your html string with the returned object's properties***
function printQuote(){
    // random object from quotes array is returned
    var randomQuoteObj = getRandomQuote();  

    // access the object's properties
    var quote = "<p class='quote'>"+ randomQuoteObj.quote +"</p>"; // change quote to randomQuoteObj.quote
        quote += "<p class='source'>"+ randomQuoteObj.source + "</p>"; // change source to randomQuoteObj.source
    document.getElementById('quote-box').innerHTML = quote;
}
Sean Lopez
Sean Lopez
6,783 Points

Very helpful.

Thanks