Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 852
Sole Avatar asked Feb 17 '26 21:02

Sole


1 Answers

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.

like image 164
see sharper Avatar answered Feb 20 '26 12:02

see sharper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!