Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 449
Srikanth Rayabhagi Avatar asked Mar 14 '26 05:03

Srikanth Rayabhagi


1 Answers

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));
like image 123
CertainPerformance Avatar answered Mar 15 '26 18:03

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!