Exception in template helper: TypeError: _.mapObject is not a function

Exception in template helper: TypeError: _.mapObject is not a function

我在 meteor 上使用 underscorejs 运行 时遇到以下问题。

"Exception in template helper: TypeError: _.mapObject is not a function"

请指教

  var types = _.groupBy(areaFlatten, 'category');
        console.log(types);
        var result = **_.mapObject**(types, function(val, key) {
        return  _.reduce(val, function(memo, v) {
          return memo + v.val;
        }, 0) / val.length * 10;

我认为您使用的是旧版本的 Underscore。 _.mapObject 已添加到 v1.8.0 (http://underscorejs.org/#changelog)

不使用 _.mapObject 的替代方案:

var types = _.groupBy(areaFlatten, 'category');
console.log(types);
var result = {};
_.each(types, function(val, key) {
    result[key] = _.reduce(val, function(memo, v) {
      return memo + v.val;
    }, 0) / val.length * 10;
});

如果您要经常使用此功能,您可以添加一个 mixin 以使该功能可用,直到您有机会升级为止,请参阅此处 https://jsfiddle.net/Lradh7jd/1/

_.mixin({
  mapObject: function(obj, iteratee, context) {
    var output = {};
    _.each(obj, function(v, k) {
        output[k] = iteratee.apply(context || this, arguments);
    });
    return output;
  }
});