修改Map中的对象的一个值

huangapple go评论90阅读模式
英文:

Change one value of an object within a Map

问题

让我们假设我有一个地图数据类型

  1. testMap: Map<string, any>;

字符串值是我的键,而any始终是该地图中的一个对象。

对象可能是这样的:

  1. { name: 'testName', age: 20 }

假设用户通过下拉菜单选择了一个带有键的元素。

现在,如何通过这个键来更改对象的名称呢?

我已经使用forEach迭代了地图,并尝试使用Map.get()Map.set()更改属性。不幸的是,这没有起作用。

英文:

Let's assume I have a map data type

  1. testMap: Map&lt;string, any&gt;

The string value is my key and any is always an object within that Map.

The object could look like this:

  1. { name: &#39;testName&#39;, age: 20}

Let's assume that the user selects an element with a key via a dropdown.

How can I now change the name of an object to the corresponding key via this key?

I already iterated over the map with forEach and tried to change a property with Map.get() and Map.set(). Unfortunately this did not work.

答案1

得分: 2

  1. // 假设你已经定义了testMap
  2. // testMap: Map<string, any>
  3. // 步骤 1:从下拉列表中获取所选的键(用实际的所选键替换'selectedKey')
  4. const selectedKey = 'someKey';
  5. // 步骤 2:从映射中检索相应的对象
  6. const selectedObject = testMap.get(selectedKey);
  7. // 步骤 3:更新对象的"name"属性
  8. if (selectedObject) {
  9. selectedObject.name = selectedKey;
  10. } else {
  11. // 处理在映射中找不到所选键的情况
  12. console.error('Selected key not found in the map!');
  13. }
  14. // 步骤 4:使用相同的键将更新后的对象放回映射中
  15. testMap.set(selectedKey, selectedObject);
  16. // 现在,映射中所选对象的"name"属性应该已更新为所选键。
英文:

Somthing like this?

  1. // Assuming you have the testMap already defined
  2. // testMap: Map&lt;string, any&gt;
  3. // Step 1: Get the selected key from the dropdown (replace &#39;selectedKey&#39; with the actual selected key)
  4. const selectedKey = &#39;someKey&#39;;
  5. // Step 2: Retrieve the corresponding object from the map
  6. const selectedObject = testMap.get(selectedKey);
  7. // Step 3: Update the &quot;name&quot; property of the object
  8. if (selectedObject) {
  9. selectedObject.name = selectedKey;
  10. } else {
  11. // Handle the case when the selected key is not found in the map
  12. console.error(&#39;Selected key not found in the map!&#39;);
  13. }
  14. // Step 4: Set the updated object back into the map using the same key
  15. testMap.set(selectedKey, selectedObject);
  16. // Now, the &quot;name&quot; property of the selected object in the map should be updated to the selected key.

huangapple
  • 本文由 发表于 2023年8月4日 01:53:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定