Skip to content Skip to sidebar Skip to footer

How To Check If Javascript Map Has An Object Key

Looking at a couple of different docs, all I see is when the Map (ECMAScript6) key is a boolean, string, or integer. Is there a way we could use another customized Object (called w

Solution 1:

You just have to save the reference to the object:

var myMap =new Map();
var myKey =new Tuple(1,1);
myMap.set( myKey, "foo");
myMap.set('bar', "foo");

myMap.has(myKey);           //returnstrue;  myKey === myKey
myMap.has(new Tuple(1,1));  //returnsfalse; new Tuple(1,1) !== myKey
myMap.has('bar');           //returnstrue;  'bar'==='bar'

Edit: Here is how to use an object to achieve what you want, which is to compare objects by their values rather than by reference:

functionTuple (x, y) {
  this.x = x;
  this.y = y;
}
Tuple.prototype.toString = function () {
  return'Tuple [' + this.x + ',' + this.y + ']';
};

var myObject = {};
myObject[newTuple(1, 1)] = 'foo';
myObject[newTuple(1, 2)] = 'bar';
console.log(myObject[newTuple(1, 1)]); // 'foo'console.log(myObject[newTuple(1, 2)]); // 'bar'

These operations will run in constant time on average, which is much faster than searching through a Map for a similar object key in linear time.

Solution 2:

When you set an object to the map, you need to pass the same memory reference when checking if the map has it.

Example:

constmap = new Map();

map.set(new Tuple(1,1));
map.has(new Tuple(1,1)) // False. You are checking a new object, not the same as the one you set.const myObject = new Tuple(1,1);
map.set(myObject);
map.has(myObject) // True. You are checking the same object.

EDIT

If you really have to do this, you could do the following:

function checkSameObjKey(map, key) {
    const keys = map.keys();
    let anotherKey;

    while(anotherKey = keys.next().value) {
         // YOUR COMPARISON HERE
         if (key.id == anotherKey.id) return true;
    }

    return false;
}

const map = new Map();
map.set({id: 1}, 1);

checkSameObjKey(map, {id: 1}); // True
checkSameObjKey(map, {id: 2}); // False

Post a Comment for "How To Check If Javascript Map Has An Object Key"