admin管理员组

文章数量:1023571

I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I acplished

var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}

Now I want to add more options for such as books, games.. so I've created an object for it:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random. And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I acplished

var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}

Now I want to add more options for such as books, games.. so I've created an object for it:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random. And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

Share Improve this question edited Mar 30, 2017 at 10:50 Devid Farinelli 7,5549 gold badges45 silver badges75 bronze badges asked Mar 30, 2017 at 10:49 TimmsterTimmster 211 silver badge2 bronze badges 2
  • Get a random number between 0 and chooseOption.length then do chooseOption.key(random number); – LiverpoolOwen Commented Mar 30, 2017 at 10:53
  • Does this answer your question? Pick random property from a Javascript object – outis Commented Nov 5, 2021 at 20:39
Add a ment  | 

4 Answers 4

Reset to default 2

So, start by writing a generic pick function that takes an array and returns an item. I'll leave the implementation of that to you.

Next you need to use Object.keys to get an array like ['watch', 'read', 'play'].

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}
var keys = Object.keys(chooseOption);
var type = pick(keys);

Then you can get the inner array by accessing the property by that key.

var items = chooseOption[type];
var item = pick(items);

And finally, display the result.

console.log('You should ' + type + ' ' + item);

use with object.keys() and Math.random()

  1. first select the random key from object using Object.keys().length.
  2. Then get the respected array of the key.
  3. Then pick the random value from the array using array length

function newMovie() {
var types =Object.keys(chooseOption);
  var rn = Math.floor(Math.random() * (types.length));
var t = types[rn];
var val = chooseOption[types[rn]];
var vn = Math.floor(Math.random() * (val.length));
var v = val[vn]
 console.log("You should watch " +t +' '+v);
}

var chooseOption = {
  watch: ["star wars", "lotr", "moonlight", "avengers"],
  read: ["scott pilgrim", "harry potter", "eragon"],
  play: ["starbound", "skyrim", "bioshock", "fallout"]
}
newMovie()

Here is another solution using Math.random() to achieve randomness:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}


function getRandom(obj, item){
  // 1) select which property to operate on.
  var itemArr = obj[item];

  // 2) we already know that the key can only be an integer(between 0 and length -1 )

  // Math.random()   : to generate a random number(between [0-1]).
  // Math.round()    : to round a number to an integer.
  // number % length : to make sure the result would be an integer between 0 and length -1 
  var index = Math.round((Math.random() * itemArr.length)) % itemArr.length;


  return {
    property:itemArr,
    index: index,
    value: itemArr[index],
  }

}


console.log(getRandom(chooseOption,'watch'));
console.log(getRandom(chooseOption,'read'));
console.log(getRandom(chooseOption,'play'));

Here you go,

    var options = {
        watch: ["star wars", "lotr", "moonlight", "avengers"],
        read: ["scott pilgrim", "harry potter", "eragon"],
        play: ["starbound", "skyrim", "bioshock", "fallout"]
    };

    for( i in options){
        //i is will be iterating with values "watch","read","play"
        t = Math.floor( Math.random()* options[i].length);
        //options[i] is to access the value of property eg: options["watch"]
        //will return ["star wars", "lotr", "moonlight", "avengers"]
        console.log("You should " + i +" "+ options[i][t]);
    }

Instead logging to something else with the code :)

I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I acplished

var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}

Now I want to add more options for such as books, games.. so I've created an object for it:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random. And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I acplished

var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}

Now I want to add more options for such as books, games.. so I've created an object for it:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random. And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

Share Improve this question edited Mar 30, 2017 at 10:50 Devid Farinelli 7,5549 gold badges45 silver badges75 bronze badges asked Mar 30, 2017 at 10:49 TimmsterTimmster 211 silver badge2 bronze badges 2
  • Get a random number between 0 and chooseOption.length then do chooseOption.key(random number); – LiverpoolOwen Commented Mar 30, 2017 at 10:53
  • Does this answer your question? Pick random property from a Javascript object – outis Commented Nov 5, 2021 at 20:39
Add a ment  | 

4 Answers 4

Reset to default 2

So, start by writing a generic pick function that takes an array and returns an item. I'll leave the implementation of that to you.

Next you need to use Object.keys to get an array like ['watch', 'read', 'play'].

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}
var keys = Object.keys(chooseOption);
var type = pick(keys);

Then you can get the inner array by accessing the property by that key.

var items = chooseOption[type];
var item = pick(items);

And finally, display the result.

console.log('You should ' + type + ' ' + item);

use with object.keys() and Math.random()

  1. first select the random key from object using Object.keys().length.
  2. Then get the respected array of the key.
  3. Then pick the random value from the array using array length

function newMovie() {
var types =Object.keys(chooseOption);
  var rn = Math.floor(Math.random() * (types.length));
var t = types[rn];
var val = chooseOption[types[rn]];
var vn = Math.floor(Math.random() * (val.length));
var v = val[vn]
 console.log("You should watch " +t +' '+v);
}

var chooseOption = {
  watch: ["star wars", "lotr", "moonlight", "avengers"],
  read: ["scott pilgrim", "harry potter", "eragon"],
  play: ["starbound", "skyrim", "bioshock", "fallout"]
}
newMovie()

Here is another solution using Math.random() to achieve randomness:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}


function getRandom(obj, item){
  // 1) select which property to operate on.
  var itemArr = obj[item];

  // 2) we already know that the key can only be an integer(between 0 and length -1 )

  // Math.random()   : to generate a random number(between [0-1]).
  // Math.round()    : to round a number to an integer.
  // number % length : to make sure the result would be an integer between 0 and length -1 
  var index = Math.round((Math.random() * itemArr.length)) % itemArr.length;


  return {
    property:itemArr,
    index: index,
    value: itemArr[index],
  }

}


console.log(getRandom(chooseOption,'watch'));
console.log(getRandom(chooseOption,'read'));
console.log(getRandom(chooseOption,'play'));

Here you go,

    var options = {
        watch: ["star wars", "lotr", "moonlight", "avengers"],
        read: ["scott pilgrim", "harry potter", "eragon"],
        play: ["starbound", "skyrim", "bioshock", "fallout"]
    };

    for( i in options){
        //i is will be iterating with values "watch","read","play"
        t = Math.floor( Math.random()* options[i].length);
        //options[i] is to access the value of property eg: options["watch"]
        //will return ["star wars", "lotr", "moonlight", "avengers"]
        console.log("You should " + i +" "+ options[i][t]);
    }

Instead logging to something else with the code :)

本文标签: htmlPick random property and value from Javascript objectStack Overflow