Exploring a Collection in Meteor: Working with an Object

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.

Answer №1

Would you like to give this a shot:

Template.scorePad.helpers({
scoresArray: function () {
    var arr = [], scores = this.scores;
    for (var key in scores) {
        var obj = {};
        obj.key = key;
        obj.value = scores[key];
        arr.push(obj);
    }
    return arr;
  }
}

Try looping through it in this manner:

<div>
{{#each scores}}
    {{this.key}}
    {{this.value}}
{{/each}}
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to execute the pdf.js node demonstrations?

I've been attempting to run the pdf.js node examples, specifically getinfo.js. Unfortunately, I encountered an issue that resulted in the following error: C:\Repositories\pdf.js>node getinfo.js node:internal/modules/cjs/loader:1080 thro ...

Generatively generating a new element for the react application to be mounted on

I am looking to enhance my JavaScript application using React by creating a build. Currently, the application consists of just a single file structured as follows. This file essentially creates a div element and continuously changes the color of the text & ...

Developing a customizable datepicker with the ability to select specific months or date ranges

I am currently developing a WebApp using flask and constructing templates in HTML/JS for the front end. I am in need of a datepicker that will provide the user with the option to choose a specific date range or select a range of months. Take a look at the ...

Storing and Manipulating a JavaScript Object with Vuex: A New Perspective

Consider a hypothetical JavaScript object class like this: class Car { var engineTurnedOn = false; ... public turnEngineOn() { engineTurnedOn = true } } If I want to turn the engine on, should I create an action called 'turnEngineOn&ap ...

Differentiating between the simple and luxurious text editing features available in the TinyMce editor

I am currently utilizing the TinyMCE editor to enhance the appearance of a textarea field where users can input comments. My goal is to offer two options for users: one for plain text and the other for a rich text editing experience. When a user selects th ...

Divide a string within a JSON object and output it as an array

I've encountered a challenge while working with data received from an API. My goal is to loop through this information and generate HTML elements based on it. The issue lies in the 'subjects' data, which arrives as a string but needs to be m ...

Swiper.IO pagination indicators not displaying

Why is the pagination not showing up on the image carousel I created with Swiper? Despite being in the DOM, it has a height of 0 and manual changes have no effect. Any suggestions? import Swiper from '../../vendor/swiper.min.js'; export default ...

Pause until various events from separate modules occur, and only then initiate the server

Currently, I am working on an application that consists of 2 distinct modules. One module deals with connecting to MongoDB while the other is responsible for connecting to Redis for session management. Each module has 2 events - error and connect. var ses ...

React client side componentDidMount function encountering issues (server side rendering)

Greetings to the Stackoverflow community Apologies in advance if my explanation is not clear enough When a user directly types a URL, the server makes a request, fetches the corresponding data, and renders it on the screen flawlessly. However, when a us ...

Using Vue: Save user information in the Vuex store prior to registration

Hello fellow members of the Stackoverflow Community, I am currently working on a Vue.js application that involves user registration. The registration process is divided into three components: Register 1 (email, password), Register 2 (personal information) ...

Implement a function in JavaScript to sum quantities for identical JSON objects

I am looking to calculate the total quantity for each category. var items = [ { cat: 'EK-1',name:"test",info:"mat", quantity: 3}, { cat: 'EK-2', name:"test2",info:"na ...

How to remove outer quotes from JSON data in Reactjs after using JSON.stringify

When using JSON.stringify on a Json data, I noticed that the resulting string includes double quotes at the beginning and end. For example: x = {fieldId: 536, value: {value: 341, display_value: "ABCD"}} After using JSON.stringify, the result looks like t ...

Encountering an issue while trying to import the instanceMethods function within Sequelize

In a file, I have written a function and exported it like this: export function foo(params...) { // do something } When initializing the model, I imported the function in the following manner: import { foo } from "../path/..." instanceMethods: { foo ...

Having trouble retrieving the recently updated data from the useReducer hook within a function defined in setTimeout

Within my application, I have encountered an issue while using a dispatch from the useReducer hook. Specifically, when I trigger a click event on a button that contains a setTimeout function of 2 seconds, the updated value is not reflected in the setTimeou ...

Achieving a dynamic "Picture Presentation" feature with JavaScript/jQuery

Currently, I am in the process of developing a website that will serve as a presentation. My plan is to create a slideshow effect using JavaScript. While I have implemented some functions, I must admit that it is not very organized at the moment. The main ...

bootstrap navigation bar collapsible menu

Struggling with making the hamburger menu appear on my friend's site. Spent hours trying to troubleshoot, but still can't figure out why it's only showing up as a red box and appearing on larger screens instead of just smaller devices. Frust ...

Compel the browser to initiate a reflow by adjusting the CSS

I am currently in the process of building a responsive image slider without relying on jQuery, using CSS3 transitions. The setup is quite simple: there's a viewport with a UL inside, containing relatively positioned LIs that are left floated. Howeve ...

Looking for a way to efficiently retrieve results by matching multiple string keywords as you go through each line of a file (fs)?

Essentially, I have multiple search strings provided by the client that need to be matched with each line in a file. If a line matches all of the inputted strings, I should add that line to the results array. However, when I run the code below, it only ret ...

Guide on Implementing Search Feature

Can anyone assist me? I am working on a search feature. Below is the code I have written along with the user stories. I have successfully implemented the first user story but facing issues with the others. Any help would be appreciated. User Stories: ...

Looping through a MongoDB collection in Node.js using Express is a straightforward process

I am currently trying to showcase a collection - within the mongo shell it is quite simple. DB = testing collection = inventory > use testing switched to db testing > db.inventory.find(); // very easy and straightforward The issue I'm fac ...