This issue has been plaguing me for some time now, and it's starting to really get on my nerves. To put it simply: How can we iterate over an object within a collection in a template?
Each entry in the collection typically looks like this:
{
"_id" : "jsWmXTvocbSMM5JAF",
"userId" : "gcko4Eo3YtZaWa8aj",
"gameId" : "eduzNj8kWv7TdiEuE",
"scores" : {
"team1" : 3,
"team2" : 1,
"losses" : 7
}
}
While we can easily access {{userId}}
or {{gameId}}
, trying to display {{scores}}
only gives us [object Object], which is expected.
I attempted using {{#each scores}}
, a method I've used with arrays before, but that resulted in an error:
{{#each}} currently only accepts arrays, cursors or falsey values.
Next, I tried a tricky approach by pushing objects into an array and returning that to the template:
Template.scorePad.helpers({
scoresArray: function () {
var arr = [], scores = this.scores;
for (var key in scores) {
var obj = {};
obj[key] = scores[key];
arr.push(obj);
}
return arr;
}
}
However, this just provided the template with an array that looked like this:
[{team1: 3}, {team2: 1}, {losses: 7}]
At this point, I could iterate over the array using #each
, but it still printed out object Object
three times, as expected. I felt like I was covering all possible bases here.
There's an unresolved issue related to being unable to use @key
with #each
on the Meteor github, but I'm hopeful someone might have a simpler solution.
This question seems somewhat relevant to what I'm dealing with, although it's not quite the same scenario.
I also attempted using #with
, with similar disappointing results.
Essentially, I'm seeking an elegant "Meteor" way of resolving this issue, if one exists. Clearly, I'm no expert. Any suggestions?
EDIT in response to comments: Just to clarify, the ideal solution (even though it doesn't work) would involve using something like this in my HTML code, so that I could iterate over each key:value pair inside the scores data within the collection:
<div>
{{#each scores}}
{{this.key}}
{{this.value}}
{{/each}}
</div>
and iterate over each key:value pair inside scores in the collection data.