1

I am new for AngularJS and I am trying to access function parameter value inside nested angular for each loop , but that variable gets undefined error. here is my code .

var pieChart = function (_data, _fieldName) {
      var data = _data;
      var cost_max = 0;
      var cost_min = 99999;

      angular.forEach(groupBy($scope.api_data, _fieldName), function (obj, index) {
          var total = 0;
          var name = '';
          angular.forEach(obj, function (row, i) {
              name = row._fieldName;
              total += 1;
          })
          data.push([name, total]);
          if (cost_max < obj.cost) cost_max = obj.cost;
          if (cost_min > obj.cost) cost_min = obj.cost;
      })
      $scope.chart.data = data;
      $scope.loaded = 1;
  }

row._fieldName is undefined here , what was the issue ? kindly help me.

  var groupBy = function (xs, key) {
      return xs.reduce(function (rv, x) {
          (rv[x[key]] = rv[x[key]] || []).push(x);
          return rv;
      }, {});
  };
2
  • Your function right at the top has a variable _fieldName too, then your forEach has a variable named _fieldName, could these perhaps be interfering with the property you want (row._fieldName)? Try naming them all something unique. Also, console.log() what obj is, see if it holds the structure/properties you expect. Commented Sep 7, 2017 at 7:00
  • the function groupBy may not be returning Array of Arrays. If it is not intended to return Array of Arrays, then check the logic. Post groupBy here if you still need help. Commented Sep 7, 2017 at 7:02

1 Answer 1

1

In your second angular.forEach loop, you have to replace row._fieldName with row[_fieldName].

angular.forEach(obj, function (row, i) {
  name = row[_fieldName];
  total += 1;
})

By writing row._fieldName, you try to get the key named _fieldName from object row instead of the real field.

Little JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.