首页 > 解决方案 > 当我们将对象作为键时,如何从 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"
      }
]

标签: javascriptecmascript-6ecmascript-2016

解决方案


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


推荐阅读