4

In typescript I defined:

class SubjectService implements ISubjectService {

    subject: any;
    subjectId: number = 0;
    subjects = {
        "1": { "id": 1, "name": "Java" },
        "100": { "id": 100, "name": "Test" }
    };

    static $inject = [
        "$http",
        "appConstant",
    ];

    constructor(
        public $http: ng.IHttpService,
        public ac: IAppConstant
        ) {
    }

}

I then in my constructor have this code:

class SubjectController {

    static $inject = [
        "$scope",
        "subjectService"
    ];

    constructor(
        public $scope,
        public su: ISubjectService
        ) {
        $scope.su = su;

        $scope.rowClicked = (subject, $index) => {
            var self = this;
            if (subject.current && subject.current == true) {
                return;
            }
            su.subjects.forEach(function (subject) {
                subject.current = false;
            });
            su.subject = subject;
            su.subject.current = true;
        }

    }

}

But when this runs I am getting a message saying:

TypeError: su.subjects.forEach is not a function at Scope.SubjectController.$scope.rowClicked (http://localhost:1810/app/controllers/SubjectController.js:12:25)

Does anyone have any idea what might be wrong. I used similar code in other places but here it fails each time.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • 1
    possible duplicate of [Why is "forEach not a function" for this map?](http://stackoverflow.com/questions/31096596/why-is-foreach-not-a-function-for-this-map) – Cerbrus Jul 01 '15 at 13:35

3 Answers3

3

subjects is an Object, not an Array, because of its {} notation. You can loop through 1 and 100 as keys if you like using Object.keys(subjects). You could also start it out as an empty array ([]) and then set the values of subjects[1] and subjects[100] if you like, but there's no shorthand inline way to just define two separated indices of an array without the inbetween ones.

Katana314
  • 8,429
  • 2
  • 28
  • 36
  • More details on the way to Object.keys(objName).forEach(...) - https://stackoverflow.com/questions/31096596/why-is-foreach-not-a-function-for-this-object/31096661 – BUDDHIKA Jun 25 '20 at 07:03
1

su.subjects is an object, not an array and forEach is not defined for Object.

phuzi
  • 12,078
  • 3
  • 26
  • 50
1

I would also note that forEach is not implemented in all versions of browsers (looking at you, IE 8) since forEach was not included until ECMA 5.1. See forEach

Josh
  • 694
  • 7
  • 10