[英]How to update the value of a javascript map with object key
I have a map with an object as a key.我有一个 map 和一个 object 作为钥匙。 For example: {date:"01/01/1990", idActiv:"4"}.
例如:{date:"01/01/1990", idActiv:"4"}。
Then as a value, I have a string ("T" or "F") that represents True or False.然后作为一个值,我有一个代表 True 或 False 的字符串(“T”或“F”)。 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"}?如何使用 object 密钥 {日期:“08/06/2020”,idActiv:“1”} 更新 map?
If I do this:如果我这样做:
mapElem.set({date: "08/06/2020", idActiv: "1"},"F");
I will have keyes repeated (Mozilla Firefox console):我将重复键(Mozilla Firefox 控制台):
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您必须将对象存储为
{date: "08/06/2020", idActiv: "1"}
单独的表达式在某处创建新实例
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.由于 Object 是引用类型,因此即使具有相同属性的 2 个对象(基本上是 2 个相同的对象)也是不同的,因为它们是 2 个不同的引用。 The following should work as they are using the same Object (same reference) as a key in the map
以下内容应该可以使用,因为它们使用相同的 Object(相同参考)作为 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 -稍后可以使用相同的引用键来更新 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或者,如果用例不需要密钥为 object,您可以在将其用作密钥之前序列化 object
JSON.stringify(object)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.