0

How do I select random value (property and its key) from the object and append each one to specific div?

    <div id="propertydiv"></div>
    <div id="valuediv"></div>

var student = {
                    name : "John Doe",
                    age : "28",
                    gender : "Male"
                };

2 Answers 2

5

If you put the object's keys in an array then you can easily select one at random, maybe a little something like this:

var student = { name : "John Doe", age : "28", gender : "Male" };

var keys = Object.keys(student);
var randomKey = keys[Math.floor(Math.random()*keys.length)];
var randomValue = student[randomKey];

document.getElementById("propertydiv").innerHTML = randomKey;
document.getElementById("valuediv").innerHTML = randomValue;
<div id="propertydiv"></div>
<div id="valuediv"></div>

(Run the snippet above several times to see the random behaviour.)

Further reading:

Sign up to request clarification or add additional context in comments.

Comments

3

You may use it for array of object like...

<div id="propertydiv"></div>
<div id="valuediv"></div>

<script>
var student = [
                { name : "John Doe", age : "28", gender : "Male" },
                { name : "Nazmul", age : "22", gender : "Male"},
                { name : "Nadir", age : "6", gender : "Male"}
              ];

var randomObject = Math.floor(Math.random()*student.length);
var keys = Object.keys(student[randomObject]);
var randomKey = keys[Math.floor(Math.random()*keys.length)];
var randomValue = student[randomObject][randomKey];

document.getElementById("propertydiv").innerHTML = randomKey;
document.getElementById("valuediv").innerHTML = randomValue;

</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.