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

221
Visualizações
I need to get a random value in a string from JSON

I have the following code where I need to get a random value:

const namesJson = {
  "nombre1": "Raghat", 
  "nombre2": "Uhmla",
  "nombre3": "Borto"
};

const btnName = document.getElementById('btn')

btnName.onclick = function names() {
  var properties = Object.getOwnPropertyNames(namesJson);
  var index = Math.floor(Math.random() * properties.length);
  var output = {};
  output[properties[index]] = namesJson[properties[index]];
  document.getElementById("mensaje").innerHTML = JSON.stringify(output);
}
<button type="button" id="btn">Get random name</button>
<h2>Mensaje:</h2>
<div id="mensaje"></div>

With this I have {"nombre2": "Uhmla"}

I want to get the value like Uhmla, how can I do?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use Object.values in order to get an array of values, then with the random you can get the value without stringifying so without the ":

const namesJson = {
  "nombre1": "Raghat", 
  "nombre2": "Uhmla",
  "nombre3": "Borto"
};

const btnName = document.getElementById('btn')

btnName.onclick = function names() {
  var properties = Object.values(namesJson);
  var index = Math.floor(Math.random() * properties.length);
  document.getElementById("mensaje").innerHTML = properties[index];
}
<button type="button" id="btn">Get random name</button>
<h2>Mensaje:</h2>
<div id="mensaje"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this:

const namesJson = {
  "nombre1": "Raghat", 
  "nombre2": "Uhmla",
  "nombre3": "Borto"
};

const names = Object.values(namesJson); // or just ["Raghat", "Uhmla", "Borto"];

const btnName = document.getElementById('btn')

btnName.onclick = () => {
  document.getElementById("mensaje").innerHTML = 
  names[Math.floor(Math.random() * names.length)]
}
<button type="button" id="btn">Get random name</button>
<h2>Mensaje</h2>
<div id="mensaje"></div>

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