Home > database >  I need to get a random value in a string from JSON
I need to get a random value in a string from JSON

Time:02-16

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?

CodePudding user response:

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>

CodePudding user response:

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>

  • Related