What is the best way to generate a random string output from an object in JavaScript?

I'm struggling with extracting a random value from the object provided below, can anyone help me out?

const hellos = {
English: "Hello",
Japanese: "Konnichiwa",
German: "Hallo",
Spanish: "Hola",
Arabic: "Ahlan wa sahlan",
Chinese: "Nihao",
};

I want to display a random output in console for testing purposes. For example, "konnichiawa", "hola", etc.

As a beginner in JS, I find it challenging to write the code myself. Any tips or guidance would be greatly appreciated. Thank you!

Answer №1

Take a look at this solution here which selects a random key and returns the corresponding value.
Considering that the key does not hold significance in your specific case, you can simply choose a random value from the values array of the Object (Object.values(hellos)).
The linked answer provides access to both the key and value, allowing you to retrieve a value for a given random key efficiently.

const hellos = {English: "Hello",Japanese: "Konnichiwa",German: "Hallo",Spanish: "Hola",Arabic: "Ahlan wa sahlan",Chinese: "Nihao",};
var randomVal = function (obj) {
    var vals = Object.values(obj);
    return vals[ vals.length * Math.random() << 0];
};

console.log(randomVal(hellos))

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

Generating a client-side MD5 hash for an image file in order to compare it to the hash calculated by Firebase?

Is there a way to calculate the MD5 of an image file on the client side within my Angular Map application, that will match the MD5 when I store the file on Firestore? I need to verify that a user's file matches a reference version stored in Firebase ...

Capture the onclick attribute with jQuery and then reapply it

I am facing a challenge with a page that has several calendars composed of HTML tables where each day is represented by a td. The td elements have an onClick attribute which I need to manipulate using jQuery. Specifically, I need to remove the onClick attr ...

Is it possible to utilize the output of a function to determine the styling of a div element in Vue?

Hi, I'm trying to use the v-bind:style in my div to apply the textposit function with the textpos prop as a parameter. The function should adjust the style of the div based on the value of the parameter. <div class="container" :style=&qu ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

You cannot make a hook call within the body of a function component, unless you are using useNavigate and useEffect in conjunction with axios interceptors

Currently, I am delving into React and attempting to include a Bearer token for private API calls. My approach involves writing a private axios function to intercept requests and responses. Subsequently, I invoke it in my API.js file to fetch data from the ...

Unraveling in jQuery

Struggling to properly handle the data being returned by JQuery from an API call. Currently encountering an error in the process. Is it possible to iterate through data using a JQuery loop like this? $.each(data.results, function (i, item) { // attemptin ...

The JSON file containing API data is stored within the _next folder, making it easily accessible to anyone without the need for security measures or a login in the Next

When accessing the protected user Listing page, we utilize SSR to call the api and retrieve all user records which are then rendered. However, if one were to check the Network tab in Chrome or Firefox, a JSON file containing all user data is generated and ...

Guide to switching from test mode to live mode and enabling live mode in stripe with nodejs

I have encountered an issue with the stripe form I am currently using for payments. When the form is loading, it displays "test mode" in the top right corner. I am unsure how to switch it to live mode and cannot find any option on the stripe dashboard to d ...

How to handle Object data returned asynchronously via Promises in Angular?

Upon receiving an array of Question objects, it appears as a data structure containing question categories and questions within each category. The process involves initializing the object with board: JeopardyBoard = new JeopardyBoard();. Subsequently, popu ...

Effortless 'rotational' script

I am currently developing a HTML5 Canvas game with the help of JavaScript. My aim is to create an object that smoothly transitions to a specific direction. The direction is being stored as a variable and calculated in radians. Here's how the code op ...

Determining the type of <this> in an Object extension method using TypeScript

I am attempting to incorporate a functionality similar to the let scope function found in Kotlin into TypeScript. My current strategy involves using declaration merging with the Object interface. While this approach generally works, I find myself missing ...

Choose a file at random from the folder, assigning probabilities based on the file names

When it comes to font files, they often have names like FontName-type.extension. All these files are stored in a single folder and I currently have this function: function random_font($dir = 'fonts') { $fonts = glob($dir . '/*'); ...

Change the value of a particular property in an array of objects by utilizing an inline function

I am working on updating the price field for a specific object. Below is my selectedCurrenciesArray: const [selectedSwapCurrencies, setSelectedSwapCurrencies] = useState([ { symbol: null, logo: null, price: 0 }, { ...

Issue with Trix text editor not triggering the change event

Lately, I've been facing some difficulties in getting the tirx-change event to trigger when there are changes in the content of a trix-editor. Despite using React JS for the view, I haven't been able to identify the problem. Below is the code sni ...

The process of altering a property in input data within Vue.js

I have a component called Input.vue that displays a label and an input field of some type. Here is how it looks: <template> <div class="form-element"> <label :for="inputId" :class="['form-element-tit ...

Tips for presenting random images from an assortment of pictures on a webpage

I'm looking to enhance my website by adding a unique feature - a dynamic banner that showcases various images from a specific picture pool. However, I'm unsure of how to find the right resources or documentation for this. Can you provide any guid ...

Ionic (Angular) experiencing crashes due to numerous HTTP requests being made

My template contains a list of items <ion-list class="ion-text-center"> <div *ngIf="farms$ | async as farmData"> <ion-item (click)="selectFarm(farm)" *ngFor="let farm of farmData" detail=&quo ...

Guide to effectively retrieving data from S3 and displaying a view at regular intervals of 4 seconds

In my current project, I am working on fetching a file from S3 and utilizing the data within that file to generate a map on a webpage. To achieve this task, I have set up an Express server along with the EJS templating engine for serving and rendering the ...

Developing a vue.js component library without the need for constant rebuilding after every edit

Introduction: I have created two projects using vue-cli ~4.2.0: parent-app - the main project dummylib - a library that is imported by parent-app. It contains several .vue components. Currently, parent-app functions well in dev mode with dummylib being ...

Having trouble detecting the Selection event of a Dropdown List upon loading

When a user chooses an option from the dropdown menu, I need to capture the selected item and perform an action: $("#user-list").on("change", function() { var selectedUser = $(this).find(":selected").text(); // Perform action with the selected us ...