I have a JSON object which consists of a long list of other JSON objects which have some common properties to each other such :
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 already built an html template. With the JS, I want to pick or iterate (random pick + loop) through the objects in data{} in random order , so I can fill up the HTML on the fly for each visitor. The random part is important, so each visitor likely get a different data.
Plain JavaScript or jQuery solutions will work in the context in which this is being deployed.
EDIT: Solution I implemented is below.
1. Collect all keys :
var keyArray = Object.keys(myData);
2. Shuffle function :
function shuffle(o){ //v1.0
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); // shuffle it!
3. Loop to iterate:
for (var i = 0; i < keyArray.length; ++i) {
var current = data[keyArray[i]];
... // what you want to do each time.
}
First, convert the data
object to an array (the keys on the first level will be lost), like shown here: https://stackoverflow.com/a/11474071/664108
var dataArray = $.map(data, function (value, key) { return value; });
Then shuffle the array (see How to randomize (shuffle) a JavaScript array? )
Alternatively you could just shuffle the keys and then operate on the original object. This way you also have still the keys:
var keyArray = $.map(data, function (value, key) { return key; });
shuffle(keyArray); // example (shuffle function has to be implemented, see above)
for (var i = 0; i < keyArray.length; ++i) {
var current = data[keyArray[i]];
// do stuff with current dataset
}
Addition from the comments
the key array can also be created by:
var keyArray = Object.keys(data);
But note that this only works on modern browsers, you should not use it if you want to support Internet Explorer in versions up to IE 8 (see: http://msdn.microsoft.com/en-us/library/ie/ff688127(v=vs.94).aspx )
Have you think about generating the JSON randomly already or shufflng it? Shuffle in Javascript
If you shuffle the array, you can apply foreach and you get the items in a random order. :)
Note: It might be faster to shuffle just a copy of the IDs.
Disclaimer! I asuumed that for your case you need just Pseudorandomness .
use the Object.keys function
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
more: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.