简体   繁体   中英

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 with the new CustomObject(x,y) constructor call) to be added as a key?

I am able to add an object as a key, but unable to check if the Map has the said 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 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

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);           // 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 is how to use an object to achieve what you want, which is to compare objects by their values rather than 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 run in constant time on average, which is much faster than searching through a Map for a similar object key in linear time.

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

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM