英文:
Change one value of an object within a Map
问题
让我们假设我有一个地图数据类型
testMap: Map<string, any>;
字符串值是我的键,而any
始终是该地图中的一个对象。
对象可能是这样的:
{ name: 'testName', age: 20 }
假设用户通过下拉菜单选择了一个带有键的元素。
现在,如何通过这个键来更改对象的名称呢?
我已经使用forEach
迭代了地图,并尝试使用Map.get()
和Map.set()
更改属性。不幸的是,这没有起作用。
英文:
Let's assume I have a map data type
testMap: Map<string, any>
The string value is my key and any is always an object within that Map.
The object could look like this:
{ name: 'testName', age: 20}
Let's assume that the user selects an element with a key via a dropdown.
How can I now change the name of an object to the corresponding key via this key?
I already iterated over the map with forEach and tried to change a property with Map.get() and Map.set(). Unfortunately this did not work.
答案1
得分: 2
// 假设你已经定义了testMap
// testMap: Map<string, any>
// 步骤 1:从下拉列表中获取所选的键(用实际的所选键替换'selectedKey')
const selectedKey = 'someKey';
// 步骤 2:从映射中检索相应的对象
const selectedObject = testMap.get(selectedKey);
// 步骤 3:更新对象的"name"属性
if (selectedObject) {
selectedObject.name = selectedKey;
} else {
// 处理在映射中找不到所选键的情况
console.error('Selected key not found in the map!');
}
// 步骤 4:使用相同的键将更新后的对象放回映射中
testMap.set(selectedKey, selectedObject);
// 现在,映射中所选对象的"name"属性应该已更新为所选键。
英文:
Somthing 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论