Modify a single property of an object in a Map
P粉884667022
P粉884667022 2023-08-03 10:24:02
0
1
486
<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粉884667022
P粉884667022

reply all(1)
P粉301523298

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template