3

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

FYI, there are issues with using JSON.stringify() in the way you show because: JSON.stringify({ label: 'x', name: 122 }) !== JSON.stringify({ name: 122, label: 'x' }) due to the ordering of the keys even though the keys are identical.
Yeah, if having differently ordered properties with the same values is a possibility (which is quite unusual, at least in my experience), then you'll have to resort to something involving the initial test of key.label === 'x' && key.name === 122
Oh, how good will it be when Records (currently Stage 2) come out! They would solve all these kinds of problems...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.