繁体   English   中英

JavaScript:无法获取对象的值

[英]JavaScript: Can not get hold of values of an object

这是我的代码

var dataGroupByParentCategory = function(data){
 return _.groupBy(data, function(entry){
    return entry.category.parent;
  });
};


var parentCategorySum = function(data) {  

  var result = {};
  _.forEach(_.keys(this.dataGroupByParentCategory(data)), function(parentCategory){
     var that = this;
     console.log(parentCategory);
     var s = _.reduce(that.dataGroupByParentCategory[parentCategory], function(s, entry){
           console.log('>' + entry);  // Can not see entry here
           return s + parseFloat(entry.amount);
     }, 0);

     result[parentCategory] = s;
  });

  return result;
};

数据看起来像

'data': [
        {
            'category': {
                'uri': '/categories/0b092e7c-4d2c-4eba-8c4e-80937c9e483d',
                'parent': 'Food',
                'name': 'Costco'
            },
            'amount': '15.0',
            'debit': true
        },
        {
            'category': {
                'uri': '/categories/d6c10cd2-e285-4829-ad8d-c1dc1fdeea2e',
                'parent': 'Food',
                'name': 'India Bazaar'
            },
            'amount': '10.0',
            'debit': true
        },
        {
            'category': {
                'uri': '/categories/d6c10cd2-e285-4829-ad8d-c1dc1fdeea2e',
                'parent': 'Food',
                'name': 'Sprouts'
            },
            'amount': '11.1',
            'debit': true
        }, ...

问题?

我看不到上面的代码中所示的项的值

       console.log('>' + entry);  // Can not see entry here

我正在学习JavaScript,并且不太熟悉范围的概念,这是否在这里引起问题?

看来你dataGroupByParentCategory功能是全球性的,所以你不需要使用thisthat访问它。 同样,您似乎在dataGroupByParentCategory[parentCategory]dataGroupByParentCategory[parentCategory] 它必须是dataGroupByParentCategory(parentCategory)

花了一段时间使用代码后,我意识到我做错了,现在的实际代码是

var parentCategorySum = function(data) {

  var result = {};
  var dataGroupByParent = dataGroupByParentCategory(data);
  _.forEach(_.keys(dataGroupByParent), function(parentCategory){
     var s = _.reduce(dataGroupByParent[parentCategory], function(s, entry){
           return s + parseFloat(entry.amount);
     }, 0);
     result[parentCategory] = s;
  });

  return result;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM