Sole
Sole

Reputation: 3340

Looping over Array of objects and returning random object value - JavaScript

I am trying to loop over an array of objects and display a random quote from the data, so far my code returns undefined. Any idea's why?

Code so far..

const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    for (var i = 0; i < 1; i += 1 )  {
    const randomQuote = quotesToUse[i][Math.floor(Math.random() * quotesToUse[i].quote.length)];
    document.getElementById("container").appendChild(text).append(randomQuote);
}

I am trying to display the quote (String) randomly.

Upvotes: 2

Views: 629

Answers (3)

Aaron Plocharczyk
Aaron Plocharczyk

Reputation: 2832

You can do this more readably with rando.js. Just don't forget to add the script tag to the head of your HTML document if you want to use this code.

const quotesToUse = [
  {quote: "This was the biggest quote ever - Array Object", author: "Derek Bullshido"},
  {quote: "Hey hows it going - Array Object", author: "Paul Frank"},
  {quote: "Why can I say that - Array Object", author: "Derek Paul"},
];

var randomValueFromArray = rando(quotesToUse).value;
console.log(randomValueFromArray.quote);
<script src="https://randojs.com/1.0.0.js"></script>

Upvotes: 1

Doruk Eren Aktaş
Doruk Eren Aktaş

Reputation: 2337

You can return random quotes with this function:

const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    const randomQuote = quotesToUse[Math.floor(Math.random() * quotesToUse.length)];
    const quote = document.createElement("DIV");
    quote.textContent=randomQuote.quote;
    const author = document.createElement("DIV");
    author.textContent=randomQuote.author;  document.getElementById("container").appendChild(quote).appendChild(author);
}

randomQuotes();
<div id="container"></div>

Upvotes: 1

see sharper
see sharper

Reputation: 12035

You probably want this to get the quote:

const randomQuote = quotesToUse[Math.floor(Math.random() * quotesToUse.length)].quote;

I don't know what you're trying to do with the loop.

Upvotes: 6

Related Questions