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"
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()]);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.