从 Javascript 对象中选择随机属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2532218/
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-08-23 00:47:00  来源:igfitidea点击:

Pick random property from a Javascript object

javascript

提问by Bemmu

Suppose you have a Javascript object like {'cat':'meow','dog':'woof' ...} Is there a more concise way to pick a random property from the object than this long winded way I came up with:

假设你有一个像 {'cat':'meow','dog':'woof' ...} 这样的 Javascript 对象,有没有比我想出的这种冗长的方法更简洁的方法来从对象中选择一个随机属性:

function pickRandomProperty(obj) {
    var prop, len = 0, randomPos, pos = 0;
    for (prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            len += 1;
        }
    }
    randomPos = Math.floor(Math.random() * len);
    for (prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (pos === randomPos) {
                return prop;
            }
            pos += 1;
        }
    }       
}

回答by Lawrence Whiteside

The chosen answer will work well. However, this answer will run faster:

选择的答案将运作良好。但是,这个答案会运行得更快:

var randomProperty = function (obj) {
    var keys = Object.keys(obj);
    return obj[keys[ keys.length * Math.random() << 0]];
};

回答by David Leonard

Picking a random element from a stream

从流中选择一个随机元素

function pickRandomProperty(obj) {
    var result;
    var count = 0;
    for (var prop in obj)
        if (Math.random() < 1/++count)
           result = prop;
    return result;
}

回答by kennytm

You can just build an array of keys while walking through the object.

您可以在遍历对象时构建一组键。

var keys = [];
for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        keys.push(prop);
    }
}

Then, randomly pick an element from the keys:

然后,从键中随机选择一个元素:

return keys[keys.length * Math.random() << 0];

回答by Paul J

I didn't think any of the examples were confusing enough, so here's a really hard to read example doing the same thing.

我不认为任何示例都足够令人困惑,所以这里有一个非常难以阅读的示例,它做同样的事情。

Edit:You probably shouldn't do this unless you want your coworkers to hate you.

编辑:除非你想让你的同事讨厌你,否则你可能不应该这样做。

var animals = {
    'cat': 'meow',
    'dog': 'woof',
    'cow': 'moo',
    'sheep': 'baaah',
    'bird': 'tweet'
};

// Random Key
console.log(Object.keys(animals)[Math.floor(Math.random()*Object.keys(animals).length)]);

// Random Value
console.log(animals[Object.keys(animals)[Math.floor(Math.random()*Object.keys(animals).length)]]);

Explanation:

解释:

// gets an array of keys in the animals object.
Object.keys(animals) 

// This is a number between 0 and the length of the number of keys in the animals object
Math.floor(Math.random()*Object.keys(animals).length)

// Thus this will return a random key
// Object.keys(animals)[0], Object.keys(animals)[1], etc
Object.keys(animals)[Math.floor(Math.random()*Object.keys(animals).length)]

// Then of course you can use the random key to get a random value
// animals['cat'], animals['dog'], animals['cow'], etc
animals[Object.keys(animals)[Math.floor(Math.random()*Object.keys(animals).length)]]

Long hand, less confusing:

长手,不那么混乱:

var animalArray  = Object.keys(animals);
var randomNumber = Math.random();
var animalIndex  = Math.floor(randomNumber * animalArray.length);

var randomKey    = animalArray[animalIndex];
// This will course this will return the value of the randomKey
// instead of a fresh random value
var randomValue  = animals[randomKey]; 

回答by Selfish

If you are capable of using libraries, you may find that Lo-DashJS library has lots of very useful methods for such cases. In this case, go ahead and check _.sample().

如果你能够使用库,你可能会发现Lo-DashJS 库有很多非常有用的方法来处理这种情况。在这种情况下,请继续检查_.sample()

(Note Lo-Dash convention is naming the library object _. Don't forget to check installation in the same page to set it up for your project.)

(注意 Lo-Dash 约定将库对象命名为 _。不要忘记在同一页面中检查安装以针对您的项目进行设置。)

_.sample([1, 2, 3, 4]);
// → 2

In your case, go ahead and use:

在您的情况下,请继续使用:

_.sample({
    cat: 'meow',
    dog: 'woof',
    mouse: 'squeak'
});
// → "woof"

回答by Nelu

If you're using underscore.jsyou can do:

如果您使用underscore.js,您可以执行以下操作:

_.sample(Object.keys(animals));


Extra:

额外的:

If you need multiple random properties add a number:

如果您需要多个随机属性,请添加一个数字:

_.sample(Object.keys(animals), 3);

If you need a new object with only those random properties:

如果您需要一个只有这些随机属性的新对象:

const props = _.sample(Object.keys(animals), 3);
const newObject = _.pick(animals, (val, key) => props.indexOf(key) > -1);

回答by Sushant Chaudhary

Another simple way to do this would be defining a function that applies Math.random()function.

另一种简单的方法是定义一个应用Math.random()函数的函数。

This function returns a random integer that ranges from the 'min'

此函数返回一个随机整数,范围从 'min'

function getRandomArbitrary(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

Then, extract either a 'key' or a 'value' or 'both' from your Javascript object each time you supply the above function as a parameter.

然后,每次提供上述函数作为参数时,从 Javascript 对象中提取“键”或“值”或“两者”。

var randNum = getRandomArbitrary(0, 7);
var index = randNum;
return Object.key(index); // Returns a random key
return Object.values(index); //Returns the corresponding value.

回答by Sybsuper

In a JSON object you must place this:

在 JSON 对象中,您必须放置:

var object={
  "Random": function() {
    var result;
    var count = 0;
    for (var prop in this){
      if (Math.random() < 1 / ++count&&prop!="Random"){
        result = this[prop];
      }
    }
    return result;
  }
}

That function will return the inner of a random property.

该函数将返回随机属性的内部。

回答by Lol Super

You can use the following code to pick a random property from a JavaScript object:

您可以使用以下代码从 JavaScript 对象中选择一个随机属性:

function randomobj(obj) {
var objkeys = Object.keys(obj)
return objkeys[Math.floor(Math.random() * objkeys.length)]
}
var example = {foo:"bar",hi:"hello"}
var randomval = example[randomobj(example)] // will return to value
// do something