Search code examples
javascriptrandomjavascript-objectsinteraction

Check if received param is equal of name from objects and get a random value of properties from these objects


Check if received param is equal of name from objects and get a random value of properties from these objects.

Hi guys, i have one string and one object of objects like this:

var reveivedValue = '11:00:00',
var randomItem = '',
myObject = {
  '11:00:00': [ '1', '2', '3' ,'4'],
  '12:00:00': [ '5', '6', '7'],
  '13:00:00': [ '8' , '9' , '10' ]
}

And I need received in "randomItem" one random value of array where the name of object of "myObject" === "receivedValue".

I don't know how to make this interaction in objects, i just know how get the random value of arrays. So i think i need to push to another array the itens where the interaction is true. Like:

var valueMatch = ['1', '2', '3' ,'4'];
var randomItem = valueMatch[Math.floor(Math.random() * valueMatch.length)];
console.log("randomItem:", randomItem);

So, i just need to know how to interact in these objects.

With you know how to make this function simplest i'll thankful for your help :)


Solution

  • Properties of an object can be accessed using dot notation or bracket notation. Refer MDN documentation on Property accessors.

    Then you can get random item using Math.random() as you are currently doing.

    var receivedValue = '11:00:00';
    var myObject = {
      '11:00:00': ['1', '2', '3', '4'],
      '12:00:00': ['5', '6', '7'],
      '13:00:00': ['8', '9', '10']
    };
    
    var selectedValue = myObject[receivedValue];
    
    var randomItem = selectedValue[Math.floor(Math.random() * selectedValue.length)];
    
    console.log("randomItem:", randomItem);