Search code examples
node.jsfor-loopjavascript-objects

Node.js Javascipt object overwritting instead of merging


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}


Solution

  • 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