javascript 如何通过键从 JSON 字典中检索随机 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14697371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:20:36  来源:igfitidea点击:

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

javascriptjqueryjsonrandomiterator

提问by Hugolpz

I have a JSON object which consists of a long list of other JSON objects which have some common properties to each other such :

我有一个 JSON 对象,它由一长串其他 JSON 对象组成,这些对象彼此具有一些共同的属性,例如:

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.

我已经构建了一个 html 模板。使用 JS,我想以随机顺序在 data{} 中的对象中选择或迭代(随机选择 + 循环),这样我就可以为每个访问者动态填充 HTML。随机部分很重要,因此每个访问者可能会获得不同的数据。

Plain JavaScript or jQuery solutions will work in the context in which this is being deployed.

普通的 JavaScript 或 jQuery 解决方案将在部署它的上下文中工作。



EDIT:Solution I implemented is below.

编辑:我实施的解决方案如下。

1. Collect all keys :

1. 收集所有钥匙:

var keyArray = Object.keys(myData);

2. Shuffle function:

2.随机播放功能

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:

3.循环迭代:

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

采纳答案by Fabian Schmengler

First, convert the dataobject to an array (the keys on the first level will be lost), like shown here: https://stackoverflow.com/a/11474071/664108

首先,将data对象转换为数组(第一层的键将丢失),如下所示: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?)

然后对数组进行洗牌(请参阅如何随机化(洗牌)一个 JavaScript 数组?

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)

但请注意,这仅适用于现代浏览器,如果您想支持 IE 8 以下版本的 Internet Explorer,则不应使用它(请参阅:http: //msdn.microsoft.com/en-us/library/ie/ff688127 (v=vs.94).aspx)

回答by Mario Corchero

Have you think about generating the JSON randomly already or shufflng it? Shuffle in Javascript

您是否考虑过随机生成 JSON 或对其进行混洗?在 Javascript 中随机播放

If you shuffle the array, you can apply foreach and you get the items in a random order. :)

如果您对数组进行洗牌,则可以应用 foreach 并以随机顺序获取项目。:)

Note: It might be faster to shuffle just a copy of the IDs.

注意:仅随机播放 ID 的副本可能会更快。

Disclaimer! I asuumed that for your case you need just Pseudorandomness.

免责声明!我假设对于您的情况,您只需要Pseudorandomness

回答by KARTHIKEYAN.A

use the Object.keys function

使用 Object.keys 函数

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

更多:https: //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys