2013-06-15 7 views
1

의 값의 보류를 가져올 수 없습니다 내 코드자바 스크립트 : 오브젝트 여기

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 

내가 자바 스크립트를 배우고 잘 범위의 개념에 정통하고 있지 않다 위의 코드와 같이 내가 그 여기에 문제를 일으키는되고, 항목의 값을 볼 수없는 이유는 무엇입니까?

+1

되는'루프의 this' 외부 = VAR . @daydreamer가'_.forEach'를 사용하여'dataGroupByParentCategory'의 키를 반복하고 있으므로 Underscore의'.forEach' – elclanrs

답변

0

귀하의 dataGroupByParentCategory 기능이 전역이므로, this 또는 that에 액세스 할 필요가 없습니다. 또한 dataGroupByParentCategory[parentCategory]에 오타가있는 것 같습니다. 그것은 코드로 언젠가 지출 후 dataGroupByParentCategory(parentCategory)

+0

'dataGroupByParentCategory [parentCategory]'가'this '가 내부에 있는지 확실하지 않습니다. 또한, 이름으로 뭔가를 참조하지 않는 데는 많은 이유가 있습니다. -1 – Ryan

+0

'dataGroupByParentCategory'는 키를 가진 객체가 아닌 함수입니다. 그는'dataGroupByParentCategory' 함수의 "result"키를 반복합니다. 또한 @daydreamer는 그의 답변에서'dataGroupByParent'라는 값을 설정함으로써 코드를 수정합니다. –

+0

a) 함수는 * 객체입니다. b)'dataGroupByParentCategory (parentCategory) '를 더 이상 답변으로 만들지 않습니다. – Ryan

0

을해야합니다, 제가 잘못하고 있었는데 실현, 실제 코드는 지금은 당신이 필요로 추측하고있어

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; 
};