Navigating the depths of an eclectic array

Looking for help with my JavaScript code:

 
var wordSelection = [
{ 'word': "Pomme", "gender": "m" },
{ "word": "Banane", "gender": "f" },
{ "word": "Ananas", "gender": "m" },
{ "word": "Chat", "gender": "f" },
{ "word": "Chien", "gender": "m" },
{ "word": "Poisson", "gender": "f" }
];   

function randomWord(){
  var chosenWord = wordSelection[Math.floor(Math.random() * wordSelection.length)].word;
  document.getElementById("word").innerHTML = chosenWord;
}

Is there a way to modify this code so that it only displays a random word (e.g. pomme, banane, ananas) or gender?

Currently, the output is [object Object] which is not what I want.

Thank you!

Answer №1

Give this a shot:

let selectedWord = wordBatch[Math.floor(Math.random()*wordBatch.length)].term

Answer №2

Make sure to specifically target the word element within the object instead of selecting the entire object at once.

http://jsfiddle.net/bhlaird/HKnb3/

var wordselection = [{
    'word': "Apple",
    "gender": "m",
}, {
    "word": "Banana",
    "gender": "f",
}, {
    "word": "Pineapple",
    "gender": "m",
}, {
    "word": "Cat",
    "gender": "f",
}, {
    "word": "Dog",
    "gender": "m",
}, {
    "word": "Fish",
    "gender": "f",
},

];

function getRandomWord() {
    var chosen = wordselection[Math.floor(Math.random() * wordselection.length)];
    document.getElementById("word").innerHTML = chosen.word;
}

Answer №4

A new feature has been added to the randomword() function allowing you to specify whether you want to select a word or gender type.

function randomword(type) {
  var chosen=wordselection[Math.floor(Math.random()*wordselection.length)][type];
  document.getElementById("word").innerHTML += "<p>"+chosen+"</p>";
}

randomword('word');
randomword('gender');

http://jsfiddle.net/AESvG/

Answer №5

If you're uncertain about what type of information to display, it's important to clarify if you prefer a word or a gender.

To display a word:

var selected = words[Math.floor(Math.random()*words.length)].word;

Alternatively, for gender:

var selected = words[Math.floor(Math.random()*words.length)].gender;

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

The Nextjs Image was preloaded using link preload, but it remained unused after a short period following the window's load event

I've encountered an issue while working with Next.js, a React-based framework. I am attempting to display the logo.png image using the Image component provided by Next.js. My image is stored in this folder: public/img Here is the code I'm using ...

Why isn't my computed property functioning properly in Vue.js?

Exploring the code snippet provided below: new Vue({ el: '#app', computed: { myMessage: function() { return "hello"; } }, data: { message: this.myMessage }, mounted: function() { console.log(this.myMessage); ...

Utilize JavaScript and AJAX to extract XML data from a web service response

Can someone help me with parsing the XML response from a web service using AJAX? Below is my code, where 'response' holds the data returned by the web service. How can I create an XML object and parse it? $.ajax({ type: 'POST', ...

How can you create an intricate HTML table using AngularJS with data nested on various levels?

Creating a table from data with multiple levels of arrays and sub-arrays can be challenging, especially when existing solutions are limited to two levels. For instance, consider the sample data below: $scope.professors = [{ 'name': 'Alb ...

Tips for achieving a dimmed content effect on Semantic UI React within a NextJS project

I'm currently facing an issue with incorporating dimmed content into the Semantic UI React sidebar on Next.js... Here is the example of dimmed content on Semantic UI: https://i.sstatic.net/5dOGK.png This is the layout code I am using: import React, ...

A collapsible select list with checkboxes for children items

I am currently developing a website using Vue.js, HTML, and SCSS. I am looking to implement a drop-down functionality similar to the animated example provided in the gif below: https://i.stack.imgur.com/Mia2D.gif The gif demonstrates how the drop-down me ...

The Slider component in Material UI's API may not properly render when using decimal numbers as steps or marks in React

I am having trouble creating a Material UI slider in my React application. I can't figure out which property is missing. Below is the code for my React component: import * as React from 'react'; import Slider from '@material-ui/core/S ...

The Vue DevTools are functioning as expected, but there seems to be an issue

Encountering a peculiar issue where the value displayed in Vue DevTools is accurate, matching what is expected in my data. When I first click on the "Edit" button for an item, the correct value appears in the browser window as intended. However, upon clic ...

The MatTableDataSource provides a promise that includes approximately 7000 rows of data

When attempting to load a large amount of data into a MatTableDataSource, I am facing an issue. I would like to display a loader until the data is fully set, but I am unsure of when that happens. I attempted to use a promise like this: return new Promise(r ...

Add data to a size guide

My coding project involved creating a sizing chart using HTML, CSS, and JavaScript. The chart allows users to select their preferred units of measurement (metric or imperial). I used JavaScript to dynamically update the values in the chart based on the sel ...

Ways to condense list chart into a single item and utilize a select dropdown to display choices without the need to refresh the

As a novice in the realm of creating charts using pandas and converting them into JSON format, I am faced with the challenge of displaying numerous graphs while conserving space. I am seeking guidance on how to implement a filtering system to only show the ...

How to Retrieve Upload Progress via HTTP Request in PHP

Is there a way to monitor the progress of file uploads by accessing the HTTP request in PHP? If so, how can this be achieved when uploading files into a MySQL database? require('../connect_db.php'); //Collect all necessary data $name = $dbc-> ...

Is there a way to access a JSON node dynamically without relying on the eval function?

Path variables can be unpredictable, ranging from just a to a/b, and even a/b/c. My goal is to dynamically reach a node based on the path provided. The code snippet below achieves this, but I am open to exploring alternative methods that do not involve usi ...

Extract particular XML element(s) and incorporate them into an HTML webpage

Just diving in for the first time. I hope you all can bear with me. This particular issue might have similarities with others, but from what I've gathered, this is a unique problem that I'm tackling. For your information, my expertise lies in de ...

What are the ways to utilize the insertedCount function in MongoDB?

Whenever I navigate to the route "/new-article", an article gets stored in the database successfully, however, the server does not respond back to the client. Upon investigating, I found that the issue lies with the constant 'ris' missing the &ap ...

toggle the outer div along with its corresponding inner div simultaneously

On one of my pages (let's call it "page1"), I have multiple divs, some nested within others. These divs are initially hidden and toggle on when a specific link is clicked (and off when clicked again). To view a nested div, the outer div must be opened ...

Expressjs encountering a routing malfunction

I am currently delving into the world of expressjs, and I have been exploring ways to incorporate MVC structure into my project. Strangely, whenever I attempt to access localhost:3000, I am greeted with a frustrating 404 error message. My project director ...

Creating a Selectable Child Form in ReactJS that Sends Data to Parent Form

Sorry for the lack of details, I'm struggling to explain this situation clearly. I'm currently learning ReactJS and JS. In a project I am working on, I have the following requirements: There is a form where users can input text and numbers. The ...

Traverse a C array using a loop

Is there a way to loop through only elements in an array that have assignments, instead of looping through all elements? In this example, I want to iterate through only three elements rather than looping through the entire array. Are there any techniques ...

transfer information using an array

I am trying to transfer data using an array with this code for the transmitter: <script type="text/javascript"> $(function() { $(".cat_button").click(function() { var element = $(this); var test = $("#cou" ...