Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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