Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda