I have a JSON object that consists of a long list of other JSON objects that share some common properties with each other, such as:
var myData = {
"0291" : { "Firstname" : "Jeremy", "Surname" : "Dyson" },
"0398" : { "Firstnname" : "Billy", "Surname" : "Bunter" },
"6714" : { "Firstnname" : "Harry", "Surname" : "Peterson" },
"9080" : { "Firstnname" : "Barry", "secondname": "Joe", "Surname" : "Mainwaring"}
...
...
}
I have already built an html template. With JS, I want to select or repeat (random selection + loop) through the objects in the data {} in random order , so I can replenish HTML on the fly for each visitor. The random part is important, so each visitor is likely to receive different data.
A uniform JavaScript or jQuery solution will work in the context in which it is deployed.
EDIT: The solution I implemented is given below.
1. Collect all the keys:
var keyArray = Object.keys(myData);
2. Function in random order :
function shuffle(o){
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
keyArray = shuffle(keyArray);
3. Loop for iteration:
for (var i = 0; i < keyArray.length; ++i) {
var current = data[keyArray[i]];
...
}