1

I'm trying to check the map key type to determine how i should filter it. My current approach is to check myMap.keys().next().value surprisingly this seems to be undefined regardless of whether its a string, int etc.

I need to check if the key is either an integer or empty. So far i have tried this:

!key.next().value // for no key
Number.isInteger(key.next().value) // for a numbered key

None of my if-statements are triggered with these checks.

Øystein Seel
  • 917
  • 2
  • 9
  • 30

3 Answers3

3

Number.isInteger verify only when the parameter is number. if you verify Number.isInteger("1") always will return false. to verify if one key is number try use regex, example:

/^\d+$/.test(key.next().value)

this works fine in both cases /^\d+$/.test("1") and /^\d+$/.test(1)

seduardo
  • 704
  • 6
  • 6
1

This is a very common mistake while working with method chaining. map.keys() returns an iterator on which the next() call iterates. Just save the myMap.keys() return value in a variable and then call next().value to make the checks. The code would look something like this:

let myMap = new Map()

myMap.set("0", "zero")
myMap.set(1, "one")

let iterator = myMap.keys()

console.log(typeof iterator.next().value)
console.log(typeof iterator.next().value)

The above snippet works as expected but try running the following snippet. It would print both the console statements as string

let myMap = new Map()

myMap.set("0", "zero")
myMap.set(1, "one")

console.log(typeof myMap.keys().next().value)
console.log(typeof myMap.keys().next().value)
1

I'm assuming you have an Object that is a Map and you wanna filter the values based on the key Type right?

you should be using typeof on know the var type:

var test = "2"
console.log(typeof 42);
// expected output: "number"

console.log(typeof 'blubber');
// expected output: "string"

console.log(typeof true);
// expected output: "boolean"

console.log(typeof declaredButUndefinedVariable);
// expected output: "undefined";

You can do the following

var myMap = new Map([[undefined, "fffff"],["2", "uno"], [2, "doios"]]);


for (const key of myMap.keys()) { 
  if(typeof key === 'string'){
    myMap.delete(key);
  }
}

console.log(myMap)

Another approach Transform your Map into Array and then proceed on filter the result:

var myMap = new Map([[undefined, "fffff"],["2", "uno"], [2, "doios"]]);

var _typeofKey = 'string'; // you can set typeof key: number , string , boolean , symbol , undefined , object , function

var results = Array.from(a).filter(
  function(element){
    var key = element[0];
    var value = element[1];
    if(typeof key === _typeofKey){
    return true;
    }
    return false;
  }
)

// new Map without string keys
var newMap = myMap(results);