1

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.

1
  • Use a loop over all keys. There's no way out. You can also use Object.assign. Commented Sep 15, 2016 at 2:16

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

4 Comments

opts = Object.assign({}, defaults, options); is probably a bit better so that you don't override your defaults globally.
@zzzzBov It is worth mentioning that you need to be careful when using Object.assign() because it doesn't do a deep copy / clone. So it is not the same behavior of jQuery.extend(true, {}, defaults, options).
@DiegoZoracKy, and likewise you need to be careful with jQuery.extend because it does a deep copy, which also might not be what you want.
@zzzzBov yeap! 👍

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.