从Javascript对象中选择随机属性

时间:2010-03-28 07:40:06

标签: javascript

假设您有一个Javascript对象,如{'cat':'meow','dog':'woof'...} 是否有更简洁的方法从对象中选择一个随机属性,而不是我提出的这种冗长的方式:

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;
        }
    }       
}

9 个答案:

答案 0 :(得分:142)

选择的答案会很好。但是,这个答案会更快:

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

答案 1 :(得分:72)

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;
}

答案 2 :(得分:15)

您可以在穿过对象时构建一个键数组。

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

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

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

答案 3 :(得分:12)

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

编辑:除非你希望你的同事恨你,否则你可能不应该这样做。

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)]]);

说明:

// 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)]]

长手,不那么混乱:

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]; 

答案 4 :(得分:11)

如果你能够使用库,你可能会发现Lo-Dash JS库对于这种情况有很多非常有用的方法。在这种情况下,请检查_.sample()

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

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

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

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

答案 5 :(得分:2)

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

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

额外:

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

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

如果您需要一个只包含那些随机属性的新对象:

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

答案 6 :(得分:0)

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

此函数返回一个随机整数,其范围为&#39; min&#39;

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

然后,提取一个键&#39;或者一个“价值”或者&#39;两者都是&#39;每次将上述函数作为参数提供时,从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.

答案 7 :(得分:0)

您必须在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;
  }
}

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

答案 8 :(得分:0)

您可以使用以下代码从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