修改Map中的对象的一个值

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

Change one value of an object within a Map

问题

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

testMap: Map<string, any>;

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

对象可能是这样的:

{ name: 'testName', age: 20 }

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

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

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

英文:

Let's assume I have a map data type

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:

{ 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

// 假设你已经定义了testMap
// testMap: Map<string, any>

// 步骤 1:从下拉列表中获取所选的键(用实际的所选键替换'selectedKey')
const selectedKey = 'someKey';

// 步骤 2:从映射中检索相应的对象
const selectedObject = testMap.get(selectedKey);

// 步骤 3:更新对象的"name"属性
if (selectedObject) {
  selectedObject.name = selectedKey;
} else {
  // 处理在映射中找不到所选键的情况
  console.error('Selected key not found in the map!');
}

// 步骤 4:使用相同的键将更新后的对象放回映射中
testMap.set(selectedKey, selectedObject);

// 现在,映射中所选对象的"name"属性应该已更新为所选键。
英文:

Somthing like this?

// Assuming you have the testMap already defined
// testMap: Map&lt;string, any&gt;

// Step 1: Get the selected key from the dropdown (replace &#39;selectedKey&#39; with the actual selected key)
const selectedKey = &#39;someKey&#39;;

// Step 2: Retrieve the corresponding object from the map
const selectedObject = testMap.get(selectedKey);

// Step 3: Update the &quot;name&quot; property of the object
if (selectedObject) {
  selectedObject.name = selectedKey;
} else {
  // Handle the case when the selected key is not found in the map
  console.error(&#39;Selected key not found in the map!&#39;);
}

// Step 4: Set the updated object back into the map using the same key
testMap.set(selectedKey, selectedObject);

// 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:

确定