Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript simple object override by defaults

bsd

I have a simple object which I would like to override with another one, in case some of the properties do not exist in the object, it should be taken from a default preset object, might be deeply nested

Here is an example of the default settings object

defaults = {
   name : 'Joe',
   options : {
      color : 'green',
      dates : {
         from : new Date,
         to   : new Date,
      }
   }
}

Here is the provided object

settings = {
   name : 'David',
   options : {
      color : 'purple'
   }
}

Here is the expected result, a combination between the two...

final = {
   name : 'David',
   options : {
      color : 'purple',
      dates : {
         from : new Date,
         to   : new Date,
      }
   }
}

Is there a simple way to achieve this without using any external libraries? I have tried some approaches (JSON.stringify / parse / iterating over the objects / etc...) but couldn't get a clean solution... hopefully a oneliner

Any help would be much appreciated...


1 Answers

Use this $.extend(true, {}, defaults,settings). Pay attention to the order of json variable. In this case, settings will override defaults should these two variables have the same attribute.

If you are looking into pure JS answer. Here is the code.

function extend(a, b){
    for (var key in b) {
        if (b.hasOwnProperty(key))
            a[key] = b[key];
            return a;
        }
    }
}
console.log(extend(defaults,settings));
like image 183
david Avatar answered Apr 23 '26 03:04

david



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!