Traversing through an array of objects to retrieve a random value from each object - Utilizing JavaScript

I'm currently attempting to loop through an array of objects and display a random quote from the data I have. However, my code seems to be returning undefined. Any thoughts on why this might be happening?

Here's what my code looks like 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 (let 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);
}

My goal is to randomly display a quote as a string.

Answer №1

If you're looking to include a quote, try using this code snippet:

const selectedQuote = quotesToDisplay[Math.floor(Math.random() * quotesToDisplay.length)].quote;

It's unclear what purpose the loop serves in your current context.

Answer №2

If you're looking to fetch random quotes, check out this handy function:

const quotesToUse = [{
    quote: "The greatest quote of all time - Array Object",
    author: "Sam Smith",
  },
  {
    quote: "Hello there! - Array Object",
    author: "Emily Davis",
  },
  {
    quote: "What a profound statement - Array Object",
    author: "Tom Johnson",
  },
]

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

getRandomQuote();
<div id="quote-container"></div>

Answer №3

If you're looking for a more elegant solution, consider using rando.js. Remember to include the script tag in the head of your HTML document to implement this code smoothly.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Focus issue with MUI Custom Text Field when state changes

Currently, I've integrated the MUI library into my React Js application. In this project, I'm utilizing the controlled Text Field component to establish a basic search user interface. However, an unexpected issue has surfaced. Following a chang ...

Utilizing the .data() method for establishing a variable

I am facing an issue while trying to set a variable in a form using .data(). The problem is that I cannot see any output for the variable "fee" - it just appears blank. What I am trying to achieve is for the user to select a Type, enter a footage, and then ...

What is the best way to retrieve the current value of a range slider?

Having some trouble with the "angular-ranger" directive that I loaded from a repository. Can anyone assist me in figuring out how to retrieve the current value of the range slider? Any guidance or suggestions would be greatly appreciated! For reference, ...

Assign the output of an XQuery query to a variable in JavaScript

Hi, I'm facing an issue that involves using XQuery on XML data stored in a variable. Here is an example of the XML structure: <channel> <available>yes</available> <label>CNN</label> </channel> <channel> <a ...

When an href is clicked in an HTML table, I am interested in fetching the value of the first column row

When a user clicks on the "Edit" link in each row, I want to display an alert with the value of the first column in that row. For example, if I click on the "Edit" link in the first row, I should see an alert with the value of the first column in that row. ...

Tips on showcasing Javascript filter outcomes after at least 2 characters have been entered

Currently, I have implemented a filter search box that displays results as soon as a single letter is inputted. However, due to the large amount of data that needs to be filtered through, I would like the search to only show results when a minimum of two l ...

Eliminate HTML nodes that are not currently visible

I am currently developing a Vue/Vuetify application that showcases a large number of images (10-20k) in a grid view along with some additional information. These images are grouped into different sections, and clicking on an image opens an overlay displayi ...

Errors during the compilation of Webgl shaders in the Google Chrome browser

Currently, I am in the process of learning three.js by following this tutorial: . Despite the tutorial working well, I have encountered errors in my own code which seem like this: ERROR: 0:26: 'nuniform' : syntax error Three.js:325 precision hi ...

What is the correct way to position a material-ui icon within a button for proper alignment?

Is there a way to properly align the <ChevronRightIcon> within the <PrimaryButton>? I want it to appear after the button label on the right side. https://i.stack.imgur.com/dcEWo.png <PrimaryButton style={{ paddingRight: &apo ...

Transforming an array into key-value pairs where the keys are odd elements and the values are even elements

Is there a straightforward way to transform this initial array: [ "Bargain", "deal", "Consistent", "Steady; regular", "Accurately", "a thing bought or offered for sale much more cheaply than is usual or expected.", "Charge", "demand (an am ...

Is it causing issues having the same version of jQuery included multiple times?

Within my HTML file, referred to as x.html, I've included other HTML files as well. In x.html, I have integrated the jquery library version 1.4.1. It seems that this same version of jquery is also being included from the other HTML files. Even though ...

Incorporating HTML with ng-binds through transclusion

I have been developing an angular directive to enhance the functionality of ng-table by adding filtering and exporting features. The main goal is to make this directive reusable for multiple tables, which requires the <td> elements to be dynamic. To ...

Tips for selecting multiple potions from a JSON file in a React Native project

I need help with highlighting multiple options from an array in React Native. Currently, when I click on an option, it highlights that option but de-highlights the previous one. How can I modify my code to allow for selecting and highlighting multiple opti ...

Determine whether the array of an object includes any elements from another array using Lodash

Each product in the array contains a unique structure that includes an ID, name, and materials list. The materials list consists of various materials with their own IDs and names. { id: 1, name: "product 1", materials: [ { id: 1, nam ...

prompting the JavaScript hangman game to identify the letters in the "selected word"

Currently, I am on a mission to teach myself Javascript and have taken on the challenge of creating a simple hangman game. This type of project is commonly used in interviews or tests, so it seemed like a great opportunity for practice. My approach involve ...

Uploading files with node.js and express

Currently, I am following the steps outlined in this tutorial: I have successfully followed the instructions until the section where they set up the routes without actually creating any views. The tutorial states: That's it, we have completed sett ...

Retrieving JSON data using Jquery (undefined)

When attempting to retrieve a value from JSON data, I am receiving 'undefined'. $.get( baseURL + 'vacation/show/' + name_surname, function( data ) { alert(data); // returns [{"id":"1","title":"Testas","start":"2015-03-04","end":"20 ...

Using jQuery UI autocomplete with special characters

Recently, I put together a simple jQuery example utilizing jQuery UI autocomplete feature. $(function() { //autocomplete $(".selector").autocomplete({ source: "getdata.php", minLength: 1 }); }) getdata.php: <?php if (isse ...

What is the best way to ensure that JavaScript is loaded in a specific sequential order?

I'm having trouble ensuring that JS files load in the correct sequence, despite my efforts to research async and defer on various platforms. This is the structure of my code: <script src="lang.js"></script> <!--loading either ...

Adjusting SVG size based on the position of the cursor for transforming origin

My goal is to scale an SVG circle using the trackpad (by moving two fingers up and down), with the origin of the transform being the cursor position. Initially, the scaling works as intended, but on subsequent attempts, the circle changes position, which s ...