Tobias
Tobias

Reputation: 701

Iterating over map with typescript does not work

I have a Typescript Map with IDs as keys and booleans as values. I want to iterate over the map and check if at least one is true. I know it would be possible with forEach, but i want to exit the loop after the first was found.

This is my coding (according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#Iterating_over_a_Map):

        private isOneSelected(): boolean {
            for (let [key, value] of this.selectionMap) {
                if (value) {
                   return true;
                }
            }
            return false;
        }

But it is not entering the loop at all. The compiled js file looks like this:

            SelectionController.prototype.isOneSelected = function () {
            for (var _i = 0, _a = this.selectionMap; _i < _a.length; _i++) {
                var _b = _a[_i], key = _b[0], value = _b[1];
                if (value) {
                    return true;
                }
            }
            return false;
            };

I am compiling against ES6 and i am using the es6-shim typings: tsconfig file:

[...]
"compilerOptions": {
    "sourceMap": true,
    "rootDir": "./client",
    "outDir": ".tmp/client",
    "target": "ES6",
    "module": "commonjs"
},
[...]

Thanks,

Tobias

Upvotes: 2

Views: 1469

Answers (2)

Yogu
Yogu

Reputation: 9445

Map does not have a length property, that's why the compiled version does not work. You could try this.selectionMap.entries() as it directly returns the Iterable of the entries.

Upvotes: 1

Cery
Cery

Reputation: 221

if you only want to check if at least one is true, you can use

this.selectionMap.filter(i=>i.key == true).length >= 1 ;

Upvotes: 0

Related Questions