FatalKeystroke FatalKeystroke - 2 months ago 9
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.

Answer

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.

Syntax

Object.assign(target, ...sources)

Example

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"