1

I have a map with an object as a key. For example: {date:"01/01/1990", idActiv:"4"}.

Then as a value, I have a string ("T" or "F") that represents True or False. My goal is to update that value, given a key.

var mapElem = new Map();

mapElem.set({date: "08/06/2020", idActiv: "1"}, "T");
mapElem.set({date: "18/06/2020", idActiv: "3"}, "T");

How I can update the map with object key {date: "08/06/2020", idActiv: "1"}?

If I do this:

mapElem.set({date: "08/06/2020", idActiv: "1"},"F"); 

I will have keyes repeated (Mozilla Firefox console):


mapElem.set({date: "08/06/2020", idActiv: "1"},"F");
Map(3)
​
size: 3
​
<entries>
​​
0: Object { date: "08/06/2020", idActiv: "1" } → "T"
​​
1: Object { date: "18/06/2020", idActiv: "3" } → "T"
​​
2: Object { date: "08/06/2020", idActiv: "1" } → "F"
​


proera
  • 123
  • 1
  • 3
  • 14
  • 2
    Map uses a strict equality check for keys – adiga Jun 08 '20 at 11:54
  • 2
    Does this answer your question? [Using Array objects as key for ES6 Map](https://stackoverflow.com/questions/32660188/using-array-objects-as-key-for-es6-map) – Ivar Jun 08 '20 at 11:55
  • you can make use of `date` as a key if it's unique – gorak Jun 08 '20 at 11:57
  • Also relevant: [Map using tuples or objects](https://stackoverflow.com/questions/21838436/map-using-tuples-or-objects). It mentions a possible solution being value objects. However, at the time that was planned for ES7 which went out years ago without this feature. [The proposal](https://github.com/tc39/proposal-record-tuple) is currently still at stage 1. – VLAZ Jun 08 '20 at 12:07

2 Answers2

0

You have to store objects as {date: "08/06/2020", idActiv: "1"} lone expression creates new instance somewhere

const obj1 = {date: "08/06/2020", idActiv: "1"};
const obj2 = {date: "18/06/2020", idActiv: "3"}
var mapElem = new Map();

mapElem.set(obj1, "T");
// mapElem.set(obj1.valueOf(), "T"); // equivalent
mapElem.set(obj2, "T");
// mapElem.set(obj2.valueOf(), "T"); // equivalent

mapElem.set(obj1, "F"); 
// mapElem.set(obj1.valueOf(), "F"); // equivalent

console.log([...mapElem.entries()]);
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
0

Since, Object is a reference type, 2 Objects even with the same properties (basically 2 identical objects) are different, as they are 2 different references. The following should work as they are using the same Object (same reference) as a key in the map

var mapElem = new Map();

const key1 = {date: "08/06/2020", idActiv: "1"};
const key2 = {date: "18/06/2020", idActiv: "3"};

mapElem.set(key1, "T");
mapElem.set(key2, "T");

The same refernce key can be used later to update the value in the Map -

mapElem.set(key1,"F");

Alternatively, if the use case do no necessarliy require the keys to be object, you can serialize the object JSON.stringify(object) before using it as the key

Vimal Munjani
  • 280
  • 1
  • 8