randomly select value from a JavaScript object

前端 未结 2 1359
感情败类
感情败类 2021-01-25 20:55

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

    
<
相关标签:
2条回答
  • 2021-01-25 21:19

    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:

    • Object.keys()
    • Math.random()
    • Math.floor()
    0 讨论(0)
  • 2021-01-25 21:22

    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>
    
    0 讨论(0)
提交回复
热议问题