Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve random JSON object by key from JSON dictionary?

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.
}
like image 557
Hugolpz Avatar asked Feb 04 '13 23:02

Hugolpz


2 Answers

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)

like image 143
Fabian Schmengler Avatar answered Nov 02 '22 23:11

Fabian Schmengler


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.

like image 26
Mario Corchero Avatar answered Nov 02 '22 23:11

Mario Corchero