在Map中修改物件的單一屬性
P粉884667022
P粉884667022 2023-08-03 10:24:02
0
1
447
<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學習者快速成長!