How to modify object property before insertion into Blaze template?


#1

Let’s say I have the following Blaze template helper that fetches some objects from a collection:

PackageInCart: function() {
            PackageIds = Carts.findOne({SessionId: SessionID}).Packages;
            var PackageObjects = Packages.find({ _id: { $in : PackageIds } } ).fetch();         
            return PackageObjects;
    },

The PackageObjects variable contains objects that have a ‘priceperday’ property with a certain price value. In the Blaze template, I can easily print this value using:

{{#each PackageInCart}}
 <div class="price">{{priceperday}}</div>
{{/each}}

However, what if I want to modify the ‘priceperday’ value from the Helper function before it gets printed in the template? What would be the correct way to do this?

One solution that came to mind was to make a for loop that iterates over the objects and does something like Object.defineProperty() to change the priceperday property into the new value.

I want to know if there’s an easier or quicker way using Blaze methods to modify the object property that gets printed with the curly braces.


#2

u can use a global helpers

also for your PackageInCart function you can define a reactive join instead of calling one selection and then calling the other on the client


#3

@nvdb31
There is nothing preventing you from making the change in the PackageInCart function above. This won’t affect reactivity.

 PackageInCart: function() {
       PackageIds = Carts.findOne({SessionId: SessionID}).Packages;
       var PackageObjects = Packages.find({ _id: { $in : PackageIds } } ).fetch();         
       // code below added by @ramez 
       PackageObjects.forEach(function(obj) {
             obj[field] = value;
       });
       // end of code addition
       return PackageObjects;
 },