Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
How I am supposed to get a random string output from an object in JS?

I need help with the following problem: How is it possible to extract a random value from the object below?

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

random output in console to test. E.g. "konnichiawa", "hola", etc.

I couldn't write my code down, because it's still hard for me as a beginner in JS. Please kindly give me some tips. Thank you!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Checkout https://stackoverflow.com/a/15106541/13583510 which picks a random key and return the value.
Since the key doesn't seem to be important as you haven't mentioned in your case you can choose a random value from the values array of the Object (Object.values(hellos)).
The answer in the link gives access to both the key and value so you can use it as well since retrieving a value from a given random key can be achieved in constant time.

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))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!