在Map中修改对象的单个属性
P粉884667022
P粉884667022 2023-08-03 10:24:02
0
1
450
<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>
P粉884667022
P粉884667022

全部回复(1)
P粉301523298

这样的吗

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!