Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda