How do I select random value (property and its key) from the object and append each one to specific div?
<
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:
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>