首页 > 社区问答列表 >在Map中修改对象的单个属性

  在Map中修改对象的单个属性

假设我有一个映射数据类型。

testMap: Map

字符串值是我的键,而任何值都是该映射中的对象。

该对象可能如下所示:


{ name: 'testName', age: 20}

假设用户通过下拉菜单选择了一个带有键的元素。

我现在如何通过这个键将对象的名称更改为相应的键?

我已经使用forEach循环遍历了映射,并尝试使用Map.get()和Map.set()更改属性。不幸的是,这并没有起作用。


P粉884667022
P粉884667022

  • P粉301523298
  • P粉301523298   已被采纳   2023-08-04 09:03:48 1楼

    这样的吗

    // Assuming you have the testMap already defined
    // testMap: Map
    
    // 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.
    
    

    +0 添加回复