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

228
Views
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 answers
Answer question

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 Report

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