Title: HandlebarsJS How to get random values from JSON
Tags: json;handlebars.js
Question: Is there a way to get random values from a JSON file? My JSON contains a lot of content based on same musical artist, so I wanted to display data more randomly and add a show more button afterwards...
so my JSON looks something like this:
data: [{
"name" : "rihanna",
"song" : "pour it up"
},
{
"name" : "rihanna"
"song" : "diamonds"
},
{
"name" : "ladygaga"
"song" : "lovegame"
},
{
"name" : "ladygaga"
"song" : "lovegame"
},
{
"name" : "ladygaga"
"song" : "pokerface"
},
{
"name" : "ladygaga"
"song" : "alejandro"
},
{
"name" : "fergie"
"song" : "fergalicious"
},
{
"name" : "fergie"
"song" : "clumsy"
},
etc etc
So, is there a way to achieve this?


Here is another answer: Try this :)
var random = Math.floor(Math.random() * jsonObject.length);
var rData = jsonObject[random];
P.S. : Where jsonObject ist your data property.

Here is another answer: Here is how you can acheive it. PLUNKER
$(document).ready(function() {
$('button').on('click', function() {
getRandom();
var html = template(context);
$('#artistlist').html(html);
});
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
var musicArray = [{
"name": "rihanna",
"song": "pour it up"
}, {
"name": "rihanna",
"song": "diamonds"
}, {
"name": "ladygaga",
"song": "lovegame"
}, {
"name": "ladygaga",
"song": "lovegame"
}, {
"name": "ladygaga",
"song": "pokerface"
}, {
"name": "ladygaga",
"song": "alejandro"
}, {
"name": "fergie",
"song": "fergalicious"
}, {
"name": "fergie",
"song": "clumsy"
}];
var context = {
music: []
};
var musicClone = $.extend(true, [], musicArray);
function getRandom() {
var i = 2;
while (i-- &amp;&amp; musicClone.length &gt;= 1) {
var random = Math.floor(Math.random() * musicClone.length);
var data = musicClone[random];
context.music.push(data);
musicClone.splice(random, 1);
}
Comment for this answer: thats very nice!! ok so do I have to add it in a register helper? If so, how do I fetch the json in a register helper?
Comment for this answer: No need for register helper.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:10/09/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<json><handlebars.js>', 'Title': 'HandlebarsJS How to get random values from JSON', 'ViewCount': 3321, 'id': 26273283, 'user_AboutMe': None, 'user_AccountId': 4910077.0, 'user_DisplayName': 'ST80', 'user_Reputation': 3297.0, 'user_Views': 479.0, 'user_id': 3955607.0}}