0

UPDATE
Since posting this question and also the link that someone provided in the comments below, the $.extend method only goes one level deep which explains the issue i was having. Using the solution mentioned in the link below will resolve the problem.

How to deep merge instead of shallow merge?


As part of a javascript tool i am building for my internal system, i accept an object as a parameter for the Class. The object that is provided gets merged with the default settings object using the $.extend() Jquery method. The default settings object contains every option for the class which contains nested objects for things like customizations.

The issue i have is if the user updates a parameter within a nested object it seems to completely overwrite the first nested object rather than just overriding the parameter they have changed when running it through the $.extend() method. How can i make it so a user can alter a parameter within the nested object while retaining the other parameters in that nested object during the creation of the instance of the class?

The default settings object is as follows:

{
        "container": "stepperContainer",
        "customization": {
            "stepper": {
                "id": "stepperProgress",
                "classes": "container my-3",
                "show": false
            }
       }

};

The settings object i provide:

{
        "customization": {
            "stepper": {
                "show": false
            }
}

I then use the $.extend() method within the class :

class Stepper {

  defaultSettings() {
  
    return {
      "customizations": {
        "stepper": {
          "id": "stepperProgress",
          "classes": "container my-3",
          "show": true
        }
      }
    };
  }

  constructor(data) {
    this.settings = $.extend(this.defaultSettings(), data);
  }

}

stepper = new Stepper({
  "customizations": {
    "stepper": {
      "show": false
    }
  }
});

console.log(stepper.settings);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  • please have look on https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge – Yanis-git May 16 '20 at 17:31
  • yes, this is how the $ .extend () method works, it only takes care of the first level of objects, the others are deleted – Mister Jojo May 16 '20 at 17:59
  • @Yanis-git - Thanks for this. I actually came across this post shortly after posting my question and it seems to do the trick. I will update my post now to reflect that i found the solution for my questions. Cheers – Gadgetfreak May 16 '20 at 18:26

1 Answers1

0

You can use defaultComposer. Similar than $.extend but work for nested objects:

this.settings = defaultComposer(this.defaultSettings(), data);
Aral Roca
  • 5,442
  • 8
  • 47
  • 78