简体   繁体   中英

How to get key of random chosen object in JavaScript?

I'm choosing a random element from an array of objects and I don't know how to get the key of that returned value. My object looks like this:

 { "location": "LA", "id": "34", "prizes": { "1": { "prize": "Prize 1", "quantity": "6", "extracted": "" }, "3": { "prize": "Prize 3", "quantity": "10", "extracted": "" }, "4": { "prize": "Prize 4", "quantity": "10", "extracted": "" } } } 

An my code where I choose random is this:

 var prizes_by_locations = locations[id_prizes].prizes; var final_prizes = []; for(var x in prizes_by_locations){ final_prizes.push(prizes_by_locations[x]); } var prize = final_prizes[Math.floor(Math.random()*final_prizes.length)]; //here is the random chosen prize but I need to get the key too var chosen_prize = prize.prize; 

I also have to say that I first remove some elements, that's why the keys are 1, 3, 4.

Do it the other way: select a random key from the object, then you can easily also get the value:

var prizes_by_locations = locations[id_prizes].prizes;
var keys = Object.keys(prizes_by_locations);
var prize_key = keys[keys.length * Math.random() << 0];
var prize_value = prizes_by_locations[prize_key];

I hope I understood you correctly and the randomKey variable is what you need var prizes_by_locations = locations[id_prizes].prizes; var final_prizes = [];

for(var x in prizes_by_locations){
  final_prizes.push(prizes_by_locations[x]);
}
var randomKey = Math.floor(Math.random()*final_prizes.length);
var prize = final_prizes[randomKey];

//here is the random chosen prize but I need to get the key too
var chosen_prize = prize.prize;
alert('The key is:' + randomKey);
var prizes_by_locations = locations[id_prizes].prizes;
var final_prizes = [];
var keys = []

for(var x in prizes_by_locations){
  final_prizes.push({
       key: x,
       result: prizes_by_locations[x]);
}
}

var prize = final_prizes[Math.floor(Math.random()*final_prizes.length)];

//here is the random chosen prize but I need to get the key too
var chosen_prize = prize.result.prize;
var key = prize.key;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM