How to check if Javascript Map has object key

Looking at a couple of different docs, all I can see is when the map key (ECMAScript6) is boolean, string or integer. Can I use another custom object (called with a new call to the CustomObject (x, y) constructor) to be added as a key?

I can add an object as a key, but cannot check if the Map has the specified object.

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


myMap.has(?);  
myMap.has('bar');  // returns true

      

Is there a way to get around this?

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

 for(some conditions) {
 var localData = new Tuple(1,1); //Use directly if exists in myMap? 
 map.has(localData) // returns false as this is a different Tuple object. But I need it to return true
}

      

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has

+3


source to share


2 answers


You just need to keep 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);           // returns true;  myKey === myKey
myMap.has(new Tuple(1,1));  // returns false; new Tuple(1,1) !== myKey
myMap.has('bar');           // returns true;  'bar' === 'bar'

      

Edit: here's how to use an object to achieve what you want, in order to compare objects by their values, not by reference:



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

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

      

These operations will be performed on average on average, which is much faster than searching the map for a similar object in linear time.

+3


source


When you place an object on a map, you need to pass the same memory reference when checking for a map.

Example:

const map = 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 need to do this, you can 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

      

+1


source







All Articles