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

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){ //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 for iteration:

for (var i = 0; i < keyArray.length; ++i) {
    var current = data[keyArray[i]];
    ... // what you want to do each time.
}
+5
3

data ( ), : fooobar.com/questions/194577/...

var dataArray = $.map(data, function (value, key) { return value; });

(. () JavaScript?)

, . , :

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
}

:

var keyArray = Object.keys(data);

, , , Internet Explorer IE 8 (. <2 > )

+4

JSON shufflng? Javascript

, foreach, .:)

. , .

! , Pseudorandomness.

+3

use function Object.keys

var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

more details: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

0
source

All Articles