从JSON属性中选择随机值 [英] Pick random value from JSON property
问题描述
我有一个标题中描述的任务.我一定不要在我的代码中的任何地方使用数组,循环和Object.keys.我只能使用Math.random.
I have got a task that I described in title. I MUST NOT to use arrays, loops and Object.keys somewhere in my code. I can only use Math.random.
JSON文件:
{
"key": "item 1, item 2, item 3",
"key2": "abc",
"key3": "123"
}
如果没有我描述的技术,我什至无法想象如何做到这一点.如果该任务支持Object.keys,它将非常简单(但我无法将其写为答案).
I can't even imagine how to do this without technologies that i described. If the task supported Object.keys it will be very simple (but i can't write this as answer).
我可以从JSON获取的对象:
let obj = {
key: "item 1, item 2, item 3",
key2: "abc",
key3: "123"
};
我使用Object.keys(我无法使用)选择随机值的函数:
let randomProperty = function (obj) {
let keys = Object.keys(obj);
return obj[keys[ keys.length * Math.random() << 0]];
};
可以使用JSON.stringify和parse,因为它必须是JSON文件而不是我编写的对象.
JSON.stringify and parse can be used, because it must be JSON file instead object that i wrote.
请帮助!
推荐答案
使用更少的代码来改变Ivan的答案. Stringify替换器将第一个参数作为参数时间,然后第二次选择一个.
Variation on Ivan's answer with much less code. Stringify replacer counts arguments the first time, then picks one the second time.
let obj = {
key: "item 1, item 2, item 3",
key2: "abc",
key3: "123"
};
let k, n = 0;
JSON.stringify(obj, (key, value) => (key && ++n || value));
n *= Math.random();
JSON.stringify(obj, (key, value) => (key && --n | 0 || (k = key) || value));
console.log(obj[k]);
这篇关于从JSON属性中选择随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!