<p>假设我有一个映射数据类型。</p>
<pre class="brush:php;toolbar:false;">testMap: Map<string, any></pre>
<p>字符串值是我的键,而任何值都是该映射中的对象。<br /><br />该对象可能如下所示:</p><p><br /></p>
<pre class="brush:php;toolbar:false;">{ name: 'testName', age: 20}</pre>
<p>假设用户通过下拉菜单选择了一个带有键的元素。<br /><br />我现在如何通过这个键将对象的名称更改为相应的键?<br /><br />我已经使用forEach循环遍历了映射,并尝试使用Map.get()和Map.set()更改属性。不幸的是,这并没有起作用。</p><p><br /></p>
这样的吗
// Assuming you have the testMap already defined // testMap: Map<string, any> // Step 1: Get the selected key from the dropdown (replace 'selectedKey' with the actual selected key) const selectedKey = 'someKey'; // Step 2: Retrieve the corresponding object from the map const selectedObject = testMap.get(selectedKey); // Step 3: Update the "name" 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('Selected key not found in the map!'); } // Step 4: Set the updated object back into the map using the same key testMap.set(selectedKey, selectedObject); // Now, the "name" property of the selected object in the map should be updated to the selected key.