Node.js JavaScript 对象覆盖而不是合并

huangapple go评论145阅读模式
英文:

Node.js Javascipt object overwritting instead of merging

问题

我正在运行一个for...of循环。我正在使用的配置文件,config,循环两次,我想要的是将这两个配置都添加到一个JavaScript对象中。我遇到的问题是,当我尝试使用扩展语法将第一个循环的数据与第二个循环的数据合并时,第二个循环的数据覆盖了整个对象,而不是合并。(我已经删除了下面函数的无关部分)

Datasets() {
    var newObject = {};
    var config = ConfigFile;
    for (const [h_name, h_config] of Object.entries(config)) {
        var d = new datasetobj(h_name, this.configuration);       
        var mergedObj = { ...d, ...h_config }; // 这部分正常工作,按预期将这两个对象合并在一起

        console.log(newObject); // 这在第一个循环中显示一个空对象(按预期),然后在第二个循环中显示第一个循环的正确数据。

        newObject = { ...newObject, ...mergedObj }; // 在这里,与其合并对象,它正在用mergedObj覆盖整个对象
        console.log(newObject);
    }
}

我期望发生在newObject上的是:{ } -> {a} -> {ab}

但实际发生的是:{ } -> {a} -> {b}

英文:

I'm running a for...of loop. The config file I'm using, config, loops twice and what I want is to take those 2 configurations and add them both to a Javascript object. The issue I'm having is that when I go to merge the data from the first loop with the data from the second loop using the spread syntax, the data from the second loop is overwriting the whole object instead of merging. (I've taken out the irrelevant parts of the function below)

  Datasets() {
      var newObject = {};
      var config = ConfigFile;
      for (const [h_name, h_config] of Object.entries(config)) {
        var d = new datasetobj(h_name, this.configuration);       
        var mergedObj = { ...d, ...h_config }; // this works fine and merges the 2 objects together as expected
        
        console.log(newObject); // This shows an empty object the first loop (as expected), then it shows the correct data from the first loop in the second loop.
      
        newObject = { ...newObject, ...mergedObj }; // Here, instead of merging the objects, it is overwriting the entire object with mergedObj
        console.log(newObject);
      }
}

What I'm expecting to happen to newObject is: { } -> {a} -> {ab}

What's actually happening though, is: { } -> {a} -> {b}

答案1

得分: 0

问题在于这两个对象具有相同的键。这些对象应该具有一个名称,然后像这样的所有键:

objA:
key1:v1

objB:
key1:v2

但是它们都具有以下顶层的所有键:

key1:v1

key1:v2

如果两个对象具有相同的键,第一个将被第二个覆盖。我重新创建了对象的方式,一切都解决了。

英文:

The issue here was that the 2 objects had the same keys. The objects were supposed to have a name then all of the keys like this:

objA:
  key1:v1
---
objB:
  key1:v2

BUT they both had all the keys at the top level like this:

key1:v1
---
key1:v2

If 2 objects have the same keys, the first one will be overwritten by the second one. I redid the way the objects were being created and everything worked out

huangapple
  • 本文由 发表于 2020年1月3日 19:43:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578032.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定