javascript - 当我们将对象作为键时,如何从 javascript Map 中检索值?
问题描述
我正在尝试为 Javascript Map 对象中的特定键检索映射中存在的值:
它看起来像这样:
let group = new Map();
group = [
[
{
"name": "Email",
"displayText": "Email",
"description": "xyz"
},
[
{
"name": "GoogleGmail",
"displayText": "Gmail",
"description": "xyz",
"soln": "Email"
}
]
],
[
{
"name": "Documents",
"displayText": "Documents",
"description": "xyz"
},
[]
],
[
{
"name": "Files",
"displayText": "Files",
"description": "xyz"
},
[]
]
]
console.log(group.get({
"name": "Email",
"displayText": "Email",
"description": "xyz"
}));
当我这样做时,我会变得不确定。那么我们如何访问该值
[
{
"name": "GoogleGmail",
"displayText": "Gmail",
"description": "xyz",
"soln": "Email"
}
]
解决方案
该group
变量被分配了一个数组的值,而不是一个映射。这是您的代码的细分。
语句 1(分配地图)
let group = new Map();
语句 2(分配一个数组,覆盖之前的分配)
group = [
.
.
];
编辑:
另一方面,根据问题中的一个评论,您可以在下面执行此操作以获得您想要的。但实际上,使用对象作为键是非常规的。请参阅下面的代码片段:
let obj = {
"name": "Email",
"displayText": "Email",
"description": "xyz"
};
let group = new Map( [
[
obj,
[
{
"name": "GoogleGmail",
"displayText": "Gmail",
"description": "xyz",
"soln": "Email"
}
]
],
[
{
"name": "Documents",
"displayText": "Documents",
"description": "xyz"
},
[]
],
[
{
"name": "Files",
"displayText": "Files",
"description": "xyz"
},
[]
]
]);
console.log(group.get(obj));
您必须使用相同的对象,而不是看起来相同的对象,通常不建议使用对象作为键,如果必须,您应该首先考虑对它们进行字符串化 – Krzysztof Krzeszewski
推荐阅读
- git - 通过没有 SSL 的 HTTP 使用带有私有存储库的 Go 模块
- javascript - 未捕获的 typeError: .fullCalendar() 不是 fullCalendar v4 的函数
- sql - 带有“Exists”子句的子查询,其中需要从两个表中收集信息
- javascript - 使用 JavaScript 制作跨度播放音乐(mp3)
- c# - 带有 index++ 的三元运算符给出“只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句”
- python - Pandas - 首先查找标题,然后仅在 Excel 工作表上加载某些列
- python - 如何在不使用collect()和for循环的情况下将一个(IP地址)的特定部分与RDD python pyspark中另一列中的其他IP地址进行比较
- typescript - TypeScript + RequireJs + 其他库 (pdfjs)
- r - 有没有办法计算数据框列中的观察次数并将其保存为字符串?
- mongodb - 如何更快地执行此 mongoDB 查找聚合?