Looping through JSON

Hey. My question is - I have a JSON file that looks like this:

{
    {
    'quote':'Tears come from the heart and not from the brain',
    'author':'Leonardo da Vinci',
    'mood': 'sad'
},
   {
    'quote':'There’s death all around us. Everywhere we look. 1.8 people kill themselves every second. We just don’t pay attention. Until we do',
    'author': 'Cynthia Hand',
    'mood': 'sad'
}
}

And so on (it’s for Random Quote Machine challenge).
I wanna make two kinds of random choice - fully random (randomly choosing from all quotes) and cathegorically random (choosing from cathegory, i.e. sad). How do I do it? How to interate through JSON?

Hmmm… In fact, it’s a nice question =) I think it’d better to make it an object of objects, but I’m not sure what’s more suitable for the task. What do you think?

Definitely keep it an array. There are a bunch of methods for arrays that make life easier. This is how I would do it:

var quotes = [
    {
      'quote':'I am chicken!',
      'author':'Me',
      'mood': 'sad'
   },
  {
    'quote':'I am robot!',
    'author': 'Me',
    'mood': 'sad'
  },
  {
    'quote':'I am robot chicken!',
    'author': 'Me',
    'mood': 'happy'
  },
]

// Generate an random value between a min and max value inclusive.
const random = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/*
 * Filter an array based a prop and a criterion. 
 * Strict equality check should do fine for primitive types.
 */
const filter = (prop, criterion) => {
  return quotes.filter((quote) => quote[prop] === criterion);
}
// Filter only objects with a prop mood that have a value of happy.
var filterByMood = filter('mood', 'happy');
var randomFromFiltered = random(0, filterByMood.length-1);
var randomFromAll = random(0, quotes.length-1);

console.log(filterByMood[randomFromFiltered]);
console.log(quotes[randomFromAll]);

Codepen

Articles that can help:
Math.random()
Array

If you have any question feel free to ask :).

2 Likes

Thanks a lot! In fact, I have only one question - if there are any good tutorials on arrow notation, could you pls give me one? I really lack knowledge in this area.