Javascript Meteor.js:获取集合字段的总和
我收集了以下物品:Javascript Meteor.js:获取集合字段的总和,javascript,meteor,Javascript,Meteor,我收集了以下物品: Object_id: "CoQayo8QmhEJduwtr" category: "Computers" createdAt: Sat May 23 2015 17:53:30 GMT-0400 (EDT)link: "https://www.apple.com/mac-pro/" price: "4999.00" title: "Mac Pro" updatedAt: Sun May 24 2015 01:27:06 GMT-0400 (EDT) userId: "yN36
Object_id: "CoQayo8QmhEJduwtr"
category: "Computers"
createdAt: Sat May 23 2015 17:53:30 GMT-0400 (EDT)link: "https://www.apple.com/mac-pro/"
price: "4999.00"
title: "Mac Pro"
updatedAt: Sun May 24 2015 01:27:06 GMT-0400 (EDT)
userId: "yN36TFg742wZcyjQG"
我在页面上为每个用户显示了一个项目列表。如何为当前用户显示价格字段的总和?您可以使用模板帮助程序,并结合使用多个下划线函数:
Template.user.helpers({
// declare a new helper on your user page template
priceSum: function(){
// fetch every items belonging to the currently displayed user
var userItems = Items.find({
userId: this._id
}).fetch();
// extract the price property in an array
var userItemsPrices = _.pluck(userItems, "price");
// compute the sum using a simple array reduction
return _.reduce(userItemsPrices, function(sum, price){
return sum + parseFloat(price);
}, 0);
}
});
谢谢,这几乎可以工作,但我想,因为我将字段存储为字符串,所以它只是将值串联起来。将值转换为数字的最佳方法是什么?我已编辑代码,对当前迭代的价格使用
parseFloat
,以便将其转换为数字。