Modifier une seule propriété d'un objet dans une carte
P粉884667022
P粉884667022 2023-08-03 10:24:02
0
1
457
<p>Supposons que j'ai un type de données mappé. </p> <pre class="brush:php;toolbar:false;">testMap : Map<string, any></pre> <p>La valeur de chaîne est ma clé et toute valeur est un objet dans cette carte. <br /><br />L'objet pourrait ressembler à ceci :</p><p><br /></p> <pre class="brush:php;toolbar:false;">{ nom : 'testName', âge : 20}</pre> <p>Supposons que l'utilisateur sélectionne un élément avec une clé via un menu déroulant. <br /><br />Comment puis-je maintenant changer le nom de l'objet en la clé correspondante par cette clé ? <br /><br />J'ai parcouru la carte à l'aide d'une boucle forEach et j'ai essayé de modifier les propriétés à l'aide de Map.get() et Map.set(). Malheureusement, cela n'a pas fonctionné. </p><p><br /></p>
P粉884667022
P粉884667022

répondre à tous(1)
P粉301523298

Est-ce comme ça

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

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!