Retrieve a random element from a selection of objects within an Array using JavaScript

Hey fellow Developers, I'm having trouble getting a random piece of data from some objects in an Array. When I try to display it, all I see is [object Object] instead of the actual text from the object. I've tried various methods but nothing seems to work. Can anyone offer a solution? Thank you so much in advance to anyone who can help.

let bill = [
 {
   name : "Sandra",
     price : "50$",
     payment : "visa",
     cardnumber:"1234 5678 9012 3456"
 },
  {
   name : "Johnson",
     price : "200$",
     payment : "master",
     cardnumber:"1234 5678 9012 3456"
 },
 ]
 
 let get  = document.querySelector(".get");
 let first =  document.querySelector(".first");
  let second =  document.querySelector(".second");
     let third =  document.querySelector(".third");
      let fourth=  document.querySelector(".fourth");
        
get.addEventListener("click" , ()=> {
let text= bill[Math.floor(Math.random()* bill.length)];

first.innerHTML =  text;
second.innerHTML = text;
third.innerHTML =  text;
fourth.innerHTML =  text;

})
body {
 font-family:"Lato",sans-serif;
display:flex;
align-items:center;
justify-content:center;
flex-direction:column;
}
<body>

<h1>
Get latest invoice
</h1>
<button class="get">Get</button>
<table >
  <tr>
    <th>Name</th>
    <th>Price</th> 
    <th>Payment</th>
            <th>Card Number</th>

  </tr>
  <tr>
    <td class="first"></td>
    <td class="second "></td>
    <td class="third"></td>
            <td class="fourth"></td>

  </tr>
    </table>
    </body>

Answer №1

The text variable is an object, so when accessing it, you need to call its key to retrieve the data. For example, use text.name to get the name.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <style>
    body {
      font-family: "Lato", sans-serif;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }
  </style>
  <body>
    <h1>Get latest invoice</h1>
    <button class="get">Get</button>
    <table>
      <tr>
        <th>Name</th>
        <th>Price</th>
        <th>Payment</th>
        <th>Card Number</th>
      </tr>
      <tr>
        <td class="first"></td>
        <td class="second"></td>
        <td class="third"></td>
        <td class="fourth"></td>
      </tr>
    </table>
  </body>

  <script>
    let bill = [
    {
      name : "Sandra",
        price : "50$",
        payment : "visa",
        cardnumber:"1234 5678 9012 3456"
    },
      {
      name : "Johnson",
        price : "200$",
        payment : "master",
        cardnumber:"1234 5678 9012 3456"
    },
    ]

    let get  = document.querySelector(".get");
    let first =  document.querySelector(".first");
    let second =  document.querySelector(".second");
    let third =  document.querySelector(".third");
    let fourth=  document.querySelector(".fourth");

    get.addEventListener("click" , ()=> {
    let text= bill[Math.floor(Math.random()* bill.length)];
    console.log(text);

    first.innerHTML =  text.name;
    second.innerHTML = text.price;
    third.innerHTML =  text.payment;
    fourth.innerHTML =  text.cardnumber;

    })
  </script>
</html>

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

Attempting to confirm the validity of my form

I have been attempting to validate my form in JSP, but unfortunately it is not working as expected. The form runs fine, however, the function 'validatemark' from my JavaScript file is not being called. Below is a snippet of my code: <%@ ...

Is it possible to use the column (PK) as an index in the resulting array when using 'mysqli_fetch_all'?

My current code snippet looks something like this: <?php // ...More Code $result = mysqli_query($mysqli, "SELECT * FROM stock_types"); if(!$result || mysqli_num_rows($result) < 1) die('error'); $stock_types = mysqli_fetch_all($re ...

Utilizing AJAX to automatically fill out a form with information retrieved from a MySQL database

I have been attempting to automate the population of a form with data when a gymnast is selected from a dropdown box. I am aware that AJAX needs to be used for this purpose, and despite my best efforts, my lack of proficiency in Javascript has resulted in ...

Shift the "Login link" to the right side of the Bootstrap navbar

Currently working on a Django website and incorporating Bootstrap/CSS/HTML to enhance the design. I've set up a navbar menu and want the login tab on the right side. However, despite my attempts, I'm not achieving the desired outcome: The HTML ...

Implementing asynchronous loading of an image onto a webpage using JavaScript

Is it possible to asynchronously load an image specified in the src attribute of an HTML image tag? I am trying to invoke a Java class using an image src tag, but I want this to happen asynchronously without affecting the current functionality of the web ...

What are some strategies for improving the speed and efficiency of traversing an XML file with AJAX?

I am currently working with an XML file structured like this: <UUT> <DKBFile>091750</DKBFile> <part> <name>FL_U1</name> <xcoord>439</xcoord> <ycoord>132</ycoord> <width>55</width ...

Leveraging JavaScript to attach/append a query parameter to a URL

Currently, I am working with the DNN CMS platform and utilizing a module called ActionForm provided by DNNSharp to generate forms. Although there is an option in this module to display a form in a popup, I am facing a challenge in passing a query string t ...

Customize cursor using CSS

I have a div with overflow: hidden that I am making scrollable by allowing the user to click and drag the background. There are links and buttons within this space. Here is the CSS I am using for this: #div-grabscroll { cursor: url(../img/op ...

Creating individual components for <select> and <option> elements in ReactJS

I am uncertain about how references function when the select and option tags are used together. When I split them into separate React components, they stop working. How can I resolve this issue? Here is a basic example: <select> {() => ( ...

Angular variable resets to initial value after modification

Currently, I am utilizing ui-router to handle the state management for the admin segment of a project. The admin area includes the ability to browse through various categories. In this category management module, I am working on implementing a breadcrumb l ...

Information within specified dates shows all leaders

Looking to filter data based on Start Date, End Date, and HeadName. The current search query successfully filters between dates but does not properly filter the HeadName column, displaying all results instead. Sno HeadName Date Amount BillNo BillD ...

Preventing Clicks on Bootstrap Tabs

Utilizing Bootstrap 3 tabs, I am constructing a step-by-step wizard similar to the layout depicted in the image below. My objective is to restrict direct clicking on the tabs and only permit progression through the use of next/previous buttons. However, I ...

Converting array types and arrays into JSON format with Jackson

I am currently faced with the task of serializing a class similar to an RPC message to JSON using Jackson in Java. I must admit that I am completely new to Jackson. Right now, my goal is to serialize an array type into JSON. So far, I have: ObjectMapper ...

Add a data attribute to an HTML element within JSX without assigning any value

Initially, I encountered a challenge when attempting to add an attribute to a custom element/component. I found that I could only add it to non-custom elements such as div and input. https://codesandbox.io/s/react-16-966eq const dAttribute = { "data-rr-m ...

Ways to prevent users from being redirected when they press the back button on a webpage

Similar Question: How can I prevent the back button from working in IE and Firefox? I'm currently working on a single page website (DAM) that requires user authentication to enter. After logging in, if a user clicks the back button, they are dire ...

Adjust the element's height as you scroll

I am currently experimenting with a method to dynamically increase the height of an element based on user scrolling behavior. Despite trying multiple approaches, I have encountered challenges in getting it to work effectively. The concept is as follows: ...

The responsive navigation bar yielded an unforeseen outcome

Looking to create a responsive navigation bar similar to the one shown here My code successfully shows and hides the navigation items, but it's not updating the burger icon No console errors or warnings are present This is my HTML: <nav> ...

Tips for efficiently updating multiple documents in MongoDB from a collection of documents:

I am facing a scenario where I need to update character mana values efficiently. Here is the current situation: Documents to be saved: [ { character: "Elf", mana: 222 }, { character: "Human", mana: 100 }, ...

What is the best way to position images and URLs in div elements using CSS?

Currently, I am on a journey to become a Front End Developer through Udacity. As part of my learning process, I have a project that needs to be submitted. Unfortunately, I encountered some issues that I couldn't resolve on my own. Specifically, I&apos ...

An easy way to disable all items within the botnav section of Vuetify

Is there a way to efficiently manage the activation and deactivation of items in a Vuetify botnav based on different router paths? I attempted to manipulate the active.sync property to -1 when I need to deactivate a tab. However, this approach only works ...