Srikanth Rayabhagi
Srikanth Rayabhagi

Reputation: 1443

Typescript Map with objects as keys

I am trying to construct a map with object as keys and probably running to object instance related issues and would like to get some opinion here.

const x = new Map<{label: string, name: number}, string>();

x.set({label: 'x', name: 122}, 'r');
x.set({label: 'x', name: 122}, 'r1');

I can see that x is populated with two Object keys, while I am actually try to update the existing one and of course reads fail on this key as object.

My hunch is that keys are considered as two different object instances, is there a way for me to achieve this?

Upvotes: 3

Views: 4217

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

Separate objects are not ===, and a Map can hold multiple objects that are not === even if they contain the same keys and values.

You can search through the keys of the Map to find one with the same label and name, and set it if it exists:

const x = new Map();

x.set({label: 'x', name: 122}, 'r');

const newVal = 'r1';
const foundObj = [...x.keys()].find(
  key => key.label === 'x' && key.name === 122
);
if (foundObj) {
  x.set(foundObj, newVal);
} else {
  x.set({label: 'x', name: 122}, newVal);
}

console.log(x.get(foundObj));

That said, this is pretty verbose. Consider if you can use a plain object instead of a Map, whose keys are the stringified objects:

const x = {};

x[JSON.stringify({label: 'x', name: 122})] = 'r'

x[JSON.stringify({label: 'x', name: 122})] = 'r1'

console.log(Object.values(x));

Upvotes: 3

Related Questions