为什么我的代码表现得像我在字典中有重复的键,尽管使用了唯一的字符串? Javascript / 附言

Why is my code behaving like I have duplicate keys in a dictionary despite using unique strings? Javascript / Appscript

我正在尝试遍历客户字典并保存能源使用数据,但是对于某些客户,当我尝试更改其使用字典中的值时,它也会更改完全不同的客户值。我有一个包含客户实用程序信息的嵌套字典,顶级键是唯一的内部 ID。

我将我的代码简化为一个循环,遍历顶级键并将字典中所有客户的同一个月的使用情况设置为迭代器的值。之后,如以下代码示例所示,我记录了三个客户的值。之后,我只增加其中一个客户的使用量,并再次记录这些值。控制台显示超过两个客户的字典以某种方式捆绑在一起,但我不知道为什么或如何解决这个问题。我也无法辨别链接客户的密钥中的任何模式。


Structure of the nested dictionary:

CustDict = 
{"N0100000XXXXXX" = 
   {"name" = "XXXX"},
   {"address" = "XXXX"},
   {"meter_read_dates" = 
      {"2021-05-13" =
         {"usage" = "XXXX"}
      }
   }
}

我用来尽可能简单地演示正在发生的事情的精简代码(真实 ID 值):

Logger.log(custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000000419887"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000012580668"]["meter_read_dates"]["2021-05-13"]["usage"])


custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"] = 
custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"] + 1

Logger.log(custDict["N01000009700816"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000000419887"]["meter_read_dates"]["2021-05-13"]["usage"])
Logger.log(custDict["N01000012580668"]["meter_read_dates"]["2021-05-13"]["usage"])

控制台输出:

11:54:56 AM Info    346.0
11:54:56 AM Info    346.0
11:54:56 AM Info    322.0
11:54:56 AM Info    347.0
11:54:56 AM Info    347.0
11:54:56 AM Info    322.0

用于创建 CustDict 字典的代码:

stmtCR = conn.prepareStatement('SELECT cust_id, utility_account, cycle_id, read_cycle FROM customers')
results = stmtCR.executeQuery()
resultsMetaData = results.getMetaData()
numCols = resultsMetaData.getColumnCount();
results.last();
numRows = results.getRow();
i = 0
results.first()  
var custDict = {}

while (i < numRows) 
{
  custDict[results.getString(1)] = {}
  custDict[results.getString(1)]["id"] = results.getString(1)
  custDict[results.getString(1)]["utility_account"] = results.getString(2)
  custDict[results.getString(1)]["cycle_id"] = results.getString(3)
  custDict[results.getString(1)]["read_cycle"] = results.getString(4)
  results.next()
  i++;
}

for (i = 0; i < Object.keys(custDict).length; i++)
{
  tempCust = custDict[Object.keys(custDict)[i]]
  tempCycleId = tempCust["cycle_id"]
  tempReadCycle = tempCust["read_cycle"]
  tempCust["meter_read_dates"] = cycleIdShdDict[tempCycleId][tempReadCycle]
  custDict[Object.keys(custDict)[i]] = tempCust 
}

cycleIdShdDict 是一个单独的字典,其中包含一组与每个 cycle_idread_cycle

关联的日期

我怀疑问题在于 Object.keys(custDict)for 循环中的不同位置以不同的顺序返回密钥。因此,您从一个键获取对象,然后将其分配给另一个键。

无需重新分配给 custDict[Object.keys(custDict)[i]],因为您正在就地修改对象,而不是副本。

但是不是遍历键,而是遍历值并修改它们。

Object.values(custDict).forEach(tempCust => {
  let tempCycleId = tempCust["cycle_id"];
  let tempReadCycle = tempCust["read_cycle"];
  tempCust["meter_read_dates"] = cycleIdShdDict[tempCycleId][tempReadCycle];
});