how to get value from key in map if key is an object js

Viewed 259

How can I get a key value from a map object if my key value is an object like this example?

const map1 = new Map();
map1.set({x:0,y:0}, 'val');

console.log(map1.get({x:0,y:0}));
//output: undefined

I am creating a map of a key value key is a point an object of x and y points val is a creature from this reason is equals to 'test'. What I need to change in my code to get this test value from this key object ?

class Board {
    constructor() {
        this.map = new Map();
    }
    add(point, creature) {
        this.map.set(point, creature)

    }
    getVal(aX, aY) {
        console.log(this.map) // Map { Point { x: 0, y: 0 } => Creature {} }
        console.log(new Point(aX, aY)) //output: {x:0,y:0}
        console.log(this.map.get(new Point(aX, aY))) //output: undefined
        return this.map.get(new Point(aX, aY))
    }
}

class Point {
    constructor(aX, aY) {
        this.x = aX;
        this.y = aY;
    }
}

function test() {
    let board = new Board();
    board.add(new Point(0, 0), 'test');

    return cretureFromBoard = board.getVal(0, 0);
}
console.log('test()', test())

1 Answers

It needs to be an object whose equality is true when compared to the key, not just any object that happens to have the same structure and values.

For example:

a = {x:0,y:0};
b = {x:0,y:0};
console.log(a == b); // false

So you would need to keep your key object somewhere and use that:

const map1 = new Map();
var key = {x:0,y:0};
map1.set(key, 'val');

console.log(map1.get(key)); // "val"

Or use something else, with more convenient equality semantics, for the key.

Related