qts
qts

Reputation: 1044

Handlebars: query and sum

How do I add the desired fields in a mongo subdocument in handlebars?

For example if my array is:

var fruits=[{ _id: 1, fruit: 'banana', number: 1 },{ _id: 2, fruit: 'Apple', number: 1 }]

and I want to add all the numbers together by doing something like this:

app.engine('handlebars', exphbs({
defaultLayout: 'mainlayout',
helpers: {
    addfruit: function(fruit){
        var addfruit="";
        for (each fruit){
            addfruit+=fruit.number;
            return addfruit;
        }
    },
};

My html:

<div><p>You have {{addfruit fruits}} in your fridge</p></div>

Any help is greatly appreciated!

Upvotes: 3

Views: 4337

Answers (2)

qts
qts

Reputation: 1044

Thanks for the guidance. Here's what I ended up doing:

 getTotal: function(fruit){

        var myfruit = fruit.map(function(item) {
            return item.length;
        });

        var total=myfruit.reduce(function(prev,curr){
            return prev+curr},0);
        return total;   
 }

Upvotes: 0

chridam
chridam

Reputation: 103435

In your helper function, use the JavaScript reduce() method to sum the number field of the objects in the fruits array, something like the following should suffice:

app.engine('handlebars', exphbs({
    defaultLayout: 'mainlayout',
    helpers: {
        getTotal: function (fruits){
            var total = fruits.reduce(function (a, b) { return a + b.number; }, 0);
            return total;
        }   
    }
});

And then in your html:

<div><p>You have {{getTotal fruits}} in your fridge</p></div>

Upvotes: 3

Related Questions