FatalKeystroke FatalKeystroke - 1 month ago 7
Javascript Question

Compare Javacript object against "default" version?

Is there a way in Javascript to check if an object fits a sort of "template" without just checking each value individually?

i.e. I am loading a config.json file in a node.js app which I need to make sure has all of the necessary config options and fill with defaults for those that aren't present. I would prefer to just have a "default" config object and compare the loaded object against it and fill the missing data with the data from the default rather than comparing each individual key.


you can use Object.assign to override defaults. this is the native solution for this problem, before that people used underscore's "mixin" and jquery's "extend" to get this behavior.


Object.assign(target, ...sources)


var defaults = {
   name: defaultName

function Factory(options={}) {
  this.settings = Object.assign({}, defaults, options);
Factory.prototype.getName = function() {
   return this.settings.name;

var myFactory = new Factory({name: "myFactory"});
myFactory.getName(); //returns "myFactory"