Hello!
stuff = (
{
'whatever': 'good day'
},
{
'whatever': 'welcome'
}
)
Template.hello.helpers({
stuffs: function () {
return stuff(random a 'whatever' here please)
}
});
How do i return a random json object?
Hello!
stuff = (
{
'whatever': 'good day'
},
{
'whatever': 'welcome'
}
)
Template.hello.helpers({
stuffs: function () {
return stuff(random a 'whatever' here please)
}
});
How do i return a random json object?
First if you want stuff
to be an array you have to use brackets []
instead of parentheses ()
. At the most basic level what you’re really asking is how to return a random array index.
You could do:
stuff[ Math.floor(Math.random() * stuff.length) ]
If you want to return a specific property of the object at the array index:
stuff[ Math.floor(Math.random() * stuff.length) ]['property']
As said above, all this does is return a random index from the array. It could be a string, an object – anything you can put in an array. Also that’s just an object literal; I believe JSON uses double quote marks.
Awesome, works like a baus. I Greatly appreciate your help.
Have a great evening.
Hmm. How would i solve the same problem but while im grabbing from a mongodb instead?
Exactly the same way. Grab your documents from your db and pick a random index in the array in the same way.
Or you can use the meteor random
package:
meteor add random
And use
Random.choice(stuff);
You can use the sample function from the underscore library, that comes with meteor.
var stuff = [{'whatever': "Hello!"}, {'whatever': "World!"}];
var sample = _.sample(stuff).whatever;
console.log(sample); // "Hello" or "World!"
I cant get it to work ://
In my view i just got {{quotes}} ( tried {{quotes.quote}} also )
EDIT: i just noticed that “.whatever” is completely wrong. But it doesnt work with .mkey or .quotes / .quote
im basically completely clueless
It’d be nice if you post the error you are getting. Anyway, you are passing a cursor to the sample() function. Use .fetch()
and it should work.
atm im getting .whatever / .quotes / (the thing i put after sample(stuff)…) is not defined
Where should i put .fetch()?
Call .fetch()
on the cursor returned by .find()
. Then, assuming it exists, you can access the “whatever” property of each array index in the array returned by fetch