search

Home  >  Q&A  >  body text

Modify a single property of an object in a Map

<p>Suppose I have a mapped data type. </p> <pre class="brush:php;toolbar:false;">testMap: Map<string, any></pre> <p>The string value is my key, and any value is an object in that map. <br /><br />The object might look like this:</p><p><br /></p> <pre class="brush:php;toolbar:false;">{ name: 'testName', age: 20}</pre> <p>Suppose the user selects an element with a key via a drop-down menu. <br /><br />How can I now change the name of the object to the corresponding key by this key? <br /><br />I have iterated through the map using a forEach loop and tried changing the properties using Map.get() and Map.set(). Unfortunately, this didn't work. </p><p><br /></p>
P粉884667022P粉884667022475 days ago490

reply all(1)I'll reply

  • P粉301523298

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

    Like this

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

    reply
    0
  • Cancelreply