Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery and Math.random() to select nested objects properties

I'm creating a random quote machine that will present a random quote from various philosophers.

I have an object literal with nested objects containing philosophers and their quotes. Using jQuery functions and Math.random(), how can I select a random quote from my object literal structure? Is there a better way to organize the data?

I've started with a jQuery closure that will display a designated quote that I'd like to modify using Math.random().

Looking for explanations to solutions as I'm a beginner. Thanks in advance.

Example object literal:

var quotes = 
{
  awatts: {
    name: "Alan Watts",
    quote: "The only way to make          sense out of change is to            plunge into it, move with it,        and join the dance."
  },
  etolle: {
    name: "Eckhart Tolle",
    quote: "Realize deeply that the       present moment is all you ever       have."
  },
  tmckenna: {
    name: "Terrence Mckenna",
    quote: "“The cost of sanity in        this society, is a certain          level of alienation” "
  }
};

Example jQuery functions with single quote selected:

    $(document).ready(function() {
        $('.mybutton').click(function() {
            $('#quote').html(quotes.awatts.quote);
        });
    });
like image 638
Lewie Avatar asked Oct 30 '22 03:10

Lewie


1 Answers

The structure of the data seems fine. You could use an array, but an object isn't a problem.

You'd get the keys from the object, and then pick a random key

var quotes = {
  awatts: {
    name: "Alan Watts",
    quote: "The only way to make          sense out of change is to            plunge into it, move with it,        and join the dance."
  },
  etolle: {
    name: "Eckhart Tolle",
    quote: "Realize deeply that the       present moment is all you ever       have."
  },
  tmckenna: {
    name: "Terrence Mckenna",
    quote: "“The cost of sanity in        this society, is a certain          level of alienation” "
  }
};

$('.mybutton').click(function() {
  var keys = Object.keys(quotes);
  var rand = keys[Math.floor(Math.random() * keys.length)];
  $('#quote').html(quotes[rand].quote);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybutton">Quote</button>
<br><br>
<div id="quote"></div>
like image 178
adeneo Avatar answered Nov 15 '22 06:11

adeneo