Heim  >  Fragen und Antworten  >  Hauptteil

Ändern Sie eine einzelne Eigenschaft eines Objekts in einer Karte

<p>Angenommen, ich habe einen zugeordneten Datentyp. </p> <pre class="brush:php;toolbar:false;">testMap: Map<string, any></pre> <p>Der Stringwert ist mein Schlüssel und jeder Wert ist ein Objekt in dieser Karte. <br /><br />Das Objekt könnte so aussehen:</p><p><br /></p> <pre class="brush:php;toolbar:false;">{ name: 'testName', age: 20}</pre> <p>Angenommen, der Benutzer wählt ein Element mit einer Taste über ein Dropdown-Menü aus. <br /><br />Wie kann ich nun mit diesem Schlüssel den Namen des Objekts in den entsprechenden Schlüssel ändern? <br /><br />Ich habe die Karte mithilfe einer forEach-Schleife durchlaufen und versucht, die Eigenschaften mithilfe von Map.get() und Map.set() zu ändern. Leider hat das nicht funktioniert. </p><p><br /></p>
P粉884667022P粉884667022444 Tage vor454

Antworte allen(1)Ich werde antworten

  • P粉301523298

    P粉3015232982023-08-04 09:03:48

    这样的吗

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

    Antwort
    0
  • StornierenAntwort