Reputation: 1044
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
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
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